I prefer to write solid shell code, so the errexit & nounset is always set.
The following code will stop at bad_command line
#!/bin/bash set -o errexit set -o nounset bad_command # stop here good_command
I want to capture it, here is my method
#!/bin/bash set -o errexit set -o nounset rc=1 bad_command && rc=0 # stop here [ $rc -ne 0 ] && do_err_handle good_command
Is there any better or cleaner method
My Answer:
#!/bin/bash set -o errexit set -o nounset if ! bad_command ; then # error handle here fi good_command
Checking Bash Exit Code Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.
The echo command is used to display the exit code for the last executed Fault Management command.
set -o errexit ( equal to set -e) The first option set -o errexit means that if any of the commands in your code fails for any reason, the entire script fails. This is particularly useful when doing Continuous Delivery pipelines.
Exit Codes. Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .
How about this? If you want the actual exit code ...
#!/bin/sh set -e cat /tmp/doesnotexist && rc=$? || rc=$? echo exitcode: $rc cat /dev/null && rc=$? || rc=$? echo exitcode: $rc
Output:
cat: /tmp/doesnotexist: No such file or directory exitcode: 1 exitcode: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With