我是 Bash 脚本新手,想知道在这种情况下处理 if-else 语句的推荐方法是什么,因为它们似乎都有效。
#!/bin/bash
bla=false
if [ "$bla" = false ]; then
echo "Method 1"
fi
if `! $bla` ; then
echo "Method 2"
fi
if [ -n $bla ] ; then
echo "Method 3"
fi
if `! $bla`;
特别糟糕,因为它尝试将空字符串作为命令运行。
但实际上,这些都不是特别好。
使用“false”和“true”可能不会达到您的想象。 shell 主要区分空字符串和非空字符串,因此也许可以使用它。
bla=""
if ! [ "$bla" ]; then
echo "Method 1, fixed"
fi
没有布尔变量的概念,但命令 true 返回零而 false 返回非零,这对 shell 来说又是有意义的。
bla=false
if ! $bla; then
echo "Method 2 fixed; but really, don't put commands in variables
fi
再次重申,
bla=false
if ! `$bla`; then
echo "Really, don't do this!"
fi
将运行
bla
,然后获取其输出(这是空字符串;false
和true
不打印任何内容)并尝试将 that 作为命令运行,并检查其退出代码。你可能只是想得很简单
if $bla; then
但再次强调,不要将命令放入变量中。
再一次,
bla='echo "crickets"'
if ! `$bla` ...
最终将运行
crickets
作为其结果代码 if
将检查的命令。