jdamae
jdamae

Reputation: 3909

shell programming - interpreting use of $? with function call

I'm trying to understand a shell/bash script and just wanted input on the use of $? in the code. Its being used with a function call.

Function example:

function showerr {   err=$1
   if [ $err -ne 0 ]; then
      echo `date` : "error!"
      echo "stat  :  " $2
      echo `date` : "stat:  " $2
      # alert email 
      prog=$0
      uname=`whoami`
      echo `date` : Sending email to ${ADDR_TO} 
      mailx -s "Error checking status " $ADDR_TO << EOF
+++++++++++++++++++++
stat   =   $2
util   =   $prog
host   =   $uname
+++++++++++++++++++++
Check $uname for details.
.
EOF
      echo "Exiting program..."
      exit 1
   fi
}

Here are some statements calling showerr. I see some within a condition (using values like 1 or any number) and some just calling it $?.

if [[ $Res = *"FileNotFound"* ]]                 
then
   echo `date` : Msg here
   showerr 1 "Msg details here"
else
   echo `date` : File: <filename> found.
fi

echo `date` :  Msg detail here 
flsz=`echo $size | cut -d'"' -f2`
showerr $? "error getting size for: (${flsz})"

Upvotes: 2

Views: 154

Answers (1)

Mat
Mat

Reputation: 206831

$? is the exit code from the last command. See Shell Command Language: Special Parameters for the list of such special variables in POSIX shells.

The showerr function logs an error if its first parameter is not 0.

So:

./some_super_script_that_might_fail
showerr $? "SuperScript failed"

will only log something if ./some_super_script_that_might_fail's exit code is not 0 (which traditionally means that it failed).

showerr 1 "message"

will always log.

showerr 0 "message"

will never do anything.

Upvotes: 6

Related Questions