我正在尝试进行简单的比较,以使用bash检查一行是否为空:
line=$(cat test.txt | grep mum )
if [ "$line" -eq "" ]
then
echo "mum is not there"
fi
Run Code Online (Sandbox Code Playgroud)
但它没有用,它说:[:太多的论点
非常感谢你的帮助!
mjs*_*ltz 26
您还可以使用$?
设置为命令返回状态的变量.所以你有:
line=$(grep mum test.txt)
if [ $? -eq 1 ]
then
echo "mum is not there"
fi
Run Code Online (Sandbox Code Playgroud)
对于grep
命令,如果有任何匹配,$?
则设置为0(干净地退出),如果没有匹配$?
则为1.
if [ ${line:-null} = null ]; then
echo "line is empty"
fi
Run Code Online (Sandbox Code Playgroud)
要么
if [ -z "${line}" ]; then
echo "line is empty"
fi
Run Code Online (Sandbox Code Playgroud)
在bash中也可以使用的经典sh答案是
if [ x"$line" = x ]
then
echo "empty"
fi
Run Code Online (Sandbox Code Playgroud)
您的问题也可能是您正在使用'-eq'进行算术比较.