Conditional Branching Based on Return Values in Bash
In bash, the return value of a called program is stored in a variable called $?
grep returns zero on a succesful match, one on no match and minus one on an error. Being able to read this return value enables easy conditional branching based on pattern matching, eg:
#/!bin/bash
# Branch based on pattern matching
PATTERN=$1
FILE=$2
grep $PATTERN $FILE > /dev/null
if [ $? -eq 0 ]; then
echo $PATTERN found
echo Now do something to $FILE
else echo Skipped $FILE
fi
Sure, you could use Perl or another more sophisticated scripting language to do this but the bash shell is powerful enough for most tasks.