为什么此测试条件未能在 bash 中产生预期结果?
Why is this test condition fails to produce the expected outcome in bash?
if [[ ! `cat /etc/passwd > /dev/null 2>&1` ]]; then
echo "not working"
fi
我在输出中得到 'not working'。
但是 运行 cat
命令后跟 echo $?
returns 0
,所以我预计不会看到输出。
要测试退出状态,不要使用 [[
和 `
:
if ! cat /etc/passwd > /dev/null 2>&1 ; then
echo "not working"
fi
反引号,也称为命令替换,扩展到命令的输出,这里始终为空,因为标准输出被重定向到 /dev/null。 [[ ! $string ]]
等同于 [[ ! -n $string ]]
或 [[ -z $string ]]
,即它测试 $string 是否为空,它始终为空(如上文所述)。
if [[ ! `cat /etc/passwd > /dev/null 2>&1` ]]; then
echo "not working"
fi
我在输出中得到 'not working'。
但是 运行 cat
命令后跟 echo $?
returns 0
,所以我预计不会看到输出。
要测试退出状态,不要使用 [[
和 `
:
if ! cat /etc/passwd > /dev/null 2>&1 ; then
echo "not working"
fi
反引号,也称为命令替换,扩展到命令的输出,这里始终为空,因为标准输出被重定向到 /dev/null。 [[ ! $string ]]
等同于 [[ ! -n $string ]]
或 [[ -z $string ]]
,即它测试 $string 是否为空,它始终为空(如上文所述)。