使用bash检查一行是否为空

16

我正在尝试使用Bash编写一个简单的比较来检查一行是否为空:

line=$(cat test.txt | grep mum )
if [ "$line" -eq "" ]
        then
        echo "mum is not there"
    fi

但是它没有起作用,显示:[: 参数太多

非常感谢您的帮助!

7个回答

27

你还可以使用设置为命令返回状态的 $? 变量。因此,你会有:

line=$(grep mum test.txt)
if [ $? -eq 1 ]
    then
    echo "mum is not there"
fi

使用 grep 命令,如果有匹配项,则 $? 被设置为 0(干净退出),如果没有匹配项,则 $? 被设置为 1。


4
您可以直接使用if grep -q mum test.txt; then ...语句。 - Daenyth
1
在这种特定的情况下,这个方法确实有效。但是,尝试添加几个管道符号,看看这种技术的效果如何。 - Anders
1
@Anders,假设您想测试管道中最后一个命令的退出状态,那么该技术完全有效。 - glenn jackman

8
if [ ${line:-null} = null ]; then
    echo "line is empty"
fi

或者

if [ -z "${line}" ]; then
    echo "line is empty"
fi

@schot,是的,你说得对,这就是为什么我也包括了第二个选项。选择一个你知道不会出现的数据输入的任意选择。否则只需选择第二个选项。Pike和Kernighan在《UNIX编程环境》中更喜欢第一种选项。 - Anders
第二个应该引用变量或使用[[(在使用bash时应始终使用[[)。对于-z,它可以工作,但对于任何其他测试,如果变量为空,则会导致错误。 - Daenyth
Daenyth:如果未加引号,则即使使用-z也不一定能正常工作。尝试使用line="foo -o bar"; if [ -z $line ]; then echo "line is empty"; else echo "line is not empty"; fi - Roman Cheplyaka

5

可在bash中使用的经典sh答案为:

if [ x"$line" = x ]
then
    echo "empty"
fi

你的问题可能是你正在使用'-eq',这是用于算术比较的。

1
这是古老、过时和破损的 shell,不要在新代码中使用它。 - gniourf_gniourf

4
grep "mum" file || echo "empty"

4
if line=$(grep -s -m 1 -e mum file.txt)
then
    echo "Found line $line"
else
    echo 'Nothing found or error occurred'
fi

2

我认为最清晰的解决方案是使用正则表达式:

if [[ "$line" =~ ^$ ]]; then
    echo "line empty"
else
    echo "line not empty"
fi

-2
如果您想要使用 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';
}

1
为什么有人会想要这样做呢?此外,OP明确要求使用bash回答。 - ntrp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接