I’m trying to run some shell command if a string is not present in a text file. If I paste this line into the command line if gives me an error.
if [ $(cat textfile.txt | grep "search string") -eq "" ]; then; echo "some string"; fi;
Error:
-bash: [: -eq: unary operator expected
If you use
[]for comparison you need to use=instead of-eq. You also need some quotes.Note that
grepcan take a filename as argument so thecatis unnecessary. You can also directly use the return value ofgrep: grep returns 1 if the search string is not found.An even more compact way would be to use logical and
&&.