bash 使用bash检查一行是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3300633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if a line is empty using bash
提问by Zenet
I am trying to do a simple comparison to check if a line is empty using bash:
我正在尝试做一个简单的比较,以使用 bash 检查一行是否为空:
line=$(cat test.txt | grep mum )
if [ "$line" -eq "" ]
then
echo "mum is not there"
fi
But it is not working, it says: [: too many arguments
但它不起作用,它说:[:参数太多
Thanks a lot for your help!
非常感谢你的帮助!
回答by mjschultz
You could also use the $?
variable that is set to the return status of the command. So you'd have:
您还可以使用$?
设置为命令返回状态的变量。所以你会有:
line=$(grep mum test.txt)
if [ $? -eq 1 ]
then
echo "mum is not there"
fi
For the grep
command if there are any matches $?
is set to 0 (exited cleanly) and if there are no matches $?
is 1.
对于grep
命令,如果有任何匹配项$?
设置为 0(干净地退出),如果没有匹配项设置$?
为 1。
回答by Anders
if [ ${line:-null} = null ]; then
echo "line is empty"
fi
or
或者
if [ -z "${line}" ]; then
echo "line is empty"
fi
回答by schot
The classical sh answer that will also work in bash is
也适用于 bash 的经典 sh 答案是
if [ x"$line" = x ]
then
echo "empty"
fi
Your problem could also be that you are using '-eq' which is for arithmetic comparison.
您的问题也可能是您使用的是用于算术比较的“-eq”。
回答by ghostdog74
grep "mum" file || echo "empty"
回答by Philipp
if line=$(grep -s -m 1 -e mum file.txt)
then
echo "Found line $line"
else
echo 'Nothing found or error occurred'
fi
回答by harrison4
I think the clearest solution is using regex:
我认为最清晰的解决方案是使用正则表达式:
if [[ "$line" =~ ^$ ]]; then
echo "line empty"
else
echo "line not empty"
fi
回答by Thusitha Sumanadasa
If you want to use PHP
with this,
如果你想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';
}