tags:

views:

98

answers:

5

Hello,

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!

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

or

if [ -z "${line}" ]; then
    echo "line is empty"
fi
Anders
This incorrectly flags line="null" as an empty line.
schot
@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".
Anders
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
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`
Roman Cheplyaka
+5  A: 

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.

mjschultz
You can also just do `if grep -q mum test.txt; then ...`
Daenyth
In this specific scenario this work, indeed. However, try adding a couple of pipes and see how well this technique works.
Anders
@Anders, that technique works perfectly well, assuming you want to test the exit status of the last command in the pipeline.
glenn jackman
Add `2>/dev/null` or `-s` to suppress error messages.
Dennis Williamson
+4  A: 

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.

schot
+2  A: 
grep "mum" file || echo "empty"
ghostdog74
You don't want grep output to show, so `grep -q`
unbeli
+2  A: 
if line=$(grep -s -m 1 -e mum file.txt)
then
    echo "Found line $line"
else
    echo 'Nothing found or error occurred'
fi
Philipp
Add `2>/dev/null` or `-s` to suppress error messages.
Dennis Williamson
Thanks, d o n e.
Philipp