Reputation: 7401
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!
Upvotes: 16
Views: 37389
Reputation: 1761
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';
}
Upvotes: -2
Reputation: 8166
I think the clearest solution is using regex:
if [[ "$line" =~ ^$ ]]; then
echo "line empty"
else
echo "line not empty"
fi
Upvotes: 2
Reputation: 49802
if line=$(grep -s -m 1 -e mum file.txt)
then
echo "Found line $line"
else
echo 'Nothing found or error occurred'
fi
Upvotes: 4
Reputation: 6218
if [ ${line:-null} = null ]; then
echo "line is empty"
fi
or
if [ -z "${line}" ]; then
echo "line is empty"
fi
Upvotes: 8
Reputation: 11268
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.
Upvotes: 5
Reputation: 2026
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.
Upvotes: 27