Search code examples
shellunixzshexitexit-code

Run a command right before a script exits due to failure


Let's say there's this script

#!/bin/zsh
python -c 'a'

which will fail since a isn't defined. Just before the shell script exits, I want to run a command, say echo bye. How can that be achieved?

Flow is to be:

  • Python command above fails.
  • bye appears in terminal.
  • The zsh script exits.

I'd prefer it to affect the python command as little as possible such as indent, putting it in an if block, checking its exit code etc. In real life, the command is in fact multiple commands.


Solution

  • In the script you posted, the fact that the shell exits is unrelated to any error. The shell would exit, because the last argument hast been executed. Take for instance the script

    #!/bin/zsh
    python -c 'a'
    echo This is the End
    

    The final echo will always be exeuted, independent of the python command. To cause the script to exit, when python returns a non-zero exit code, you would write something like

    #!/bin/zsh
    python -c 'a' || exit $?
    echo Successful
    

    If you want to exit a script, whenever the first one of the commands produces a non-zeror exit status, AND at the same time want to print a message, you can use the TRAPZERR callback:

    #!/bin/zsh
    TRAPZERR() {
      echo You have an unhandled non-zero exit code in your otherwise fabulous script
      exit $?
    }
    python -c 'a'
    echo Only Exit Code 0 encountered