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})"
$?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
showerrfunction logs an error if its first parameter is not0.So:
will only log something if
./some_super_script_that_might_fail‘s exit code is not 0 (which traditionally means that it failed).will always log.
will never do anything.