我正在尝试使用Bash编写一个简单的比较来检查一行是否为空:
line=$(cat test.txt | grep mum )
if [ "$line" -eq "" ]
then
echo "mum is not there"
fi
但是它没有起作用,显示:[: 参数太多
非常感谢您的帮助!
你还可以使用设置为命令返回状态的 $?
变量。因此,你会有:
line=$(grep mum test.txt)
if [ $? -eq 1 ]
then
echo "mum is not there"
fi
使用 grep
命令,如果有匹配项,则 $?
被设置为 0(干净退出),如果没有匹配项,则 $?
被设置为 1。
if [ ${line:-null} = null ]; then
echo "line is empty"
fi
或者
if [ -z "${line}" ]; then
echo "line is empty"
fi
[[
(在使用bash时应始终使用[[
)。对于-z
,它可以工作,但对于任何其他测试,如果变量为空,则会导致错误。 - Daenythline="foo -o bar"; if [ -z $line ]; then echo "line is empty"; else echo "line is not empty"; fi
。 - Roman Cheplyaka可在bash中使用的经典sh答案为:
if [ x"$line" = x ]
then
echo "empty"
fi
grep "mum" file || echo "empty"
if line=$(grep -s -m 1 -e mum file.txt)
then
echo "Found line $line"
else
echo 'Nothing found or error occurred'
fi
我认为最清晰的解决方案是使用正则表达式:
if [[ "$line" =~ ^$ ]]; then
echo "line empty"
else
echo "line not empty"
fi
PHP
,$path_to_file='path/to/your/file';
$line = trim(shell_exec("grep 'mum' $path_to_file |wc -l"));
if($line==1){
echo 'mum is not here';
}
else{
echo 'mum is here';
}
if grep -q mum test.txt; then ...
语句。 - Daenyth