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!
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With