|
|
In addition to the explicit test or [ commands, if can make a choice on the basis of any program (or pipeline of programs) that returns a value. It is normal for programs to return ``0'' if they succeed, or another (usually negative) number if they fail; this value is retained in the variable $?, which is implicitly tested by if. It is not uncommon to see a shell script that contains commands like the following:
if who | grep -e "$1" > /dev/null then print -- $1 is logged in fiIn this example, the output from who is piped to grep. The if statement tests the output from the pipe, which is the value returned by grep. grep returns 0 if it finds the target string, or a non-zero value if it fails.
This example is therefore equivalent to a test that returns TRUE if a string is present in a given file.