16

I am trying to do a simple comparison to check if a line is empty using 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!

7 Answers 7

27

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You can also just do if grep -q mum test.txt; then ...
In this specific scenario this work, indeed. However, try adding a couple of pipes and see how well this technique works.
@Anders, that technique works perfectly well, assuming you want to test the exit status of the last command in the pipeline.
8
if [ ${line:-null} = null ]; then
    echo "line is empty"
fi

or

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

3 Comments

@schot, Yes, you're correct, which is why I included the second one also. Pick an arbitrary choice of a data input that you know won't occur. Otherwise just select the second option. Pike and Kernighan prefers the first option in "The UNIX Programming Environment".
The second one should either quote the variable or use [[ (You should always use [[ when using bash). In the case of -z it works, but for any other test, it will cause an error if the variable is empty.
Daenyth: if unquoted, it not necessary works correctly even with -z. Try line="foo -o bar"; if [ -z $line ]; then echo "line is empty"; else echo "line is not empty"; fi
5

The classical sh answer that will also work in bash is

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

Your problem could also be that you are using '-eq' which is for arithmetic comparison.

1 Comment

This is the classical for ancient, obsolete and broken shells! Please don't use this in new code.
4
grep "mum" file || echo "empty"

Comments

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

Comments

2

I think the clearest solution is using regex:

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

Comments

-2

If you want to use PHP with this,

$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 Comment

why would anybody ever want to do that? Additionally the OP explicitly requested a bash answer..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.