Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a line is empty using bash

Tags:

bash

shell

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!

like image 967
Zenet Avatar asked Jul 21 '10 14:07

Zenet


People also ask

Can Bash script have empty lines?

The first two characters of the first line should be #!, then follows the path to the shell that should interpret the commands that follow. Blank lines are also considered to be lines, so don't start your script with an empty line. As noted before, this implies that the Bash executable can be found in /bin.

How do you search for a blank line in a file?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '. How can I search in both standard input and in files?


1 Answers

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.

like image 94
mjschultz Avatar answered Sep 25 '22 13:09

mjschultz