You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
koalaman edited this page Oct 1, 2016
·
9 revisions
Use 'if cmd; then ..' to check exit code, or 'if $(cmd) == ..' to check output.
Problematic code:
if [ grep -q pattern file ]
thenecho"Found a match"fi
Correct code:
if grep -q pattern file
thenecho"Found a match"fi
Rationale:
[ .. ] 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.
[ is just regular command, like whoami or grep, but with a funny name (see ls -l /bin/[). It's a shorthand for 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