在 bash 中处理调节的推荐方法

问题描述 投票:0回答:1

我是 bash 脚本编写新手,想知道在这种情况下处理 if-else 语句的推荐方法是什么,因为它们似乎都有效。

#!/bin/bash
bla=true

if [ "$bla" = false ]; then
    echo "Method 1"
fi

if `! $bla` ; then
    echo "Method 2"
fi

if [ -n $bla ] ; then
    echo "Method 3"
fi
bash shell scripting
1个回答
0
投票

您可以使用

if
elif
条件语句(请参阅 https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html):

if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
fi

在您的示例中(请注意,

$a = false
! $a
相同,所以我更改了它):

#!/bin/bash
bla=true

if [ "$bla" = true ]; then
    echo "Method 1"
elif `! $bla` ; then
    echo "Method 2"
elif [ -n $bla ] ; then
    echo "Method 3"
fi
© www.soinside.com 2019 - 2024. All rights reserved.