我是 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
您可以使用
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