I'm fairly new to scripting and I want to learn how to check the values of $? to check whether the a grep command was successful, If the grep command is not successful, then to echo a message which includes the values of $name.  How can I achieve this, I'm aware that I can use an If statement and a special shell variable but I don't know the proper syntax. I gave it a try in the code below.name=$1         if [ $name =   ]         then  echo -n Name 'DBS' is not in directory            read name         figrep -i $name mike ~admin/dbs/emailgrep -i goodman ~admin/dbs/passwd
How to use a special shell variable in If then statements
bash;shell script
Here's some fairly typical syntax. It could do with some more error checking, but within the scope of what you're looking to do, I believe this will help you on to the right track:#!/bin/bashfile=/etc/hostsif [ -z $1 ]; then    echo Usage: $0 name 1>&2    exit 2fiif grep -q $1 $file ; then    echo $file contains $1else    echo $file doesn\'t contain $1fiNotesThe first test (if [ -z $1 ]; then ...) is true if $1 (first commandline argument) is an empty string (or was not provided).The Usage: line is output to stderr with 1>&2The output of grep itself is hidden (except for error output, which you'd probably want to see), since in this case we only want to know if it was successful (match found) or not.grep has a parameter -q that silences all output, which is the better choice here, but not all commands have a quiet switch, In those cases, you can use >/dev/null instead, as in my example below.Specific example with $?You specifically asked for an example with $?. Instead of the above if grep ... construct, we could indeed split that into separate statements:# grep -q $1 $file would work just as well, here (better, maybe!):grep $1 $file >/dev/nullif [ $? -eq 0 ]; then    echo $file contains $1else    echo $file doesn\'t contain $1fiIt's important to note that testing $? must happen immediately after the command in question, as any other commands (excluding some shell builtins) will cause the value to be overwritten.What is $?$? is simply the exit code of the last process (command) executed by the shell. By convention, a 0 exit code is success (although, as with most conventions, there are exceptions). Higher exit codes can have various meanings specific to the application, but usually non-zero means some kind of abnormal exit. Consult the documentation of the command for more information.Further readingtest(1)