Search code examples
bashunixexit-code

Why does if [ ...something... ]; then echo "Exit status is $?" always emit 0?


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?


Solution

  • In both of these cases, the last command executed was [, which exited with 0 status ("success") to land you in the "true" block.

    Yes, you need to specify a non-zero exit code for the exit command.

    Pedantically "unix" does not output the error code: it's the shell running your script that exits with the specified status.