What is the correct way to output an exit status in bash? As far as I know, the exit status called by $? corresponds to the status of the last command executed.
The script being worked on has a few conditional checks on the files fed as arguments, for example, a check on whether any files were named at all or if a file exists or not.
So I have conditional statements like this:
if [ $# -eq 0 ] ; then echo "No file name(s) given! \nExit status=$?" exit if [ ! -e "$fName" ] ; then echo "$fName does not exist! \nExit status=$?" exit But these return an exit status of 0. I'm not entirely sure even what exit codes would be appropriate for each of these situations, but I think both 1 would work for both based on this. Should I just hard-code the 1 into the conditional statement or change the logic so unix outputs an error code? Also, what command would the 0 that I get for the above example be the exit code for?
echotoo has an exit status, so by the time you get to theexit, your last exit status is that of theecho, so (presuming that theechosuccessfully wrote its output)exit's default behavior ofexit "$?"will have the effect ofexit 0, no matter what$?had been beforeechoran.echowith backslash literals is unspecified by POSIX and has behavior that various across shells (or even across runtime configurations, such as varying on the state of thexpg_echoflag in bash); see the APPLICATION USAGE section of pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html(( $# )) || { echo "ERROR: No file names given!" >&2; exit 1; }(if we're using bashisms;[ "$#" -eq 0 ] && { ...otherwise) and[[ -e $fName ]] || { echo "ERROR: Could not find $fName" >&2; exit 1; }(here, using[[rather than[to get extended syntax making quotes unnecessary; again, an extension, but an explicit one that behaves consistently across ksh-inspired shells -- bash and zsh among them -- where it's available).