Pattern: Missing use of if cmd; then ..
or if [[ $(cmd) == .. ]]
Issue: -
[ .. ]
is not part of shell syntax like if
statements. It is not equivalent to parentheses in C-like languages, if (foo) { bar; }
, and should not be wrapped around commands to test.
If you want to check the exit status of a certain command, use that command directly as demonstrated in the correct code.
If you want to check the output of a command, use "$(..)"
to get its output, and then use test
or [
/[[
to do a string comparison:
# Check output of `whoami` against the string `root`
if [ "$(whoami)" = "root" ]
then
echo "Running as root"
fi
Example of incorrect code:
if [ grep -q pattern file ]
then
echo "Found a match"
fi
Example of correct code:
if grep -q pattern file
then
echo "Found a match"
fi