Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to detect shell exit code when errexit option is set?

Tags:

bash

shell

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 
like image 728
Daniel YC Lin Avatar asked Mar 09 '12 06:03

Daniel YC Lin


People also ask

How do I find my shell exit code?

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.

Which command should I use to display the exit code of the previous command in shell?

The echo command is used to display the exit code for the last executed Fault Management command.

What is set Errexit?

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.

What is exit code in shell script?

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 .


1 Answers

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 
like image 85
rrauenza Avatar answered Oct 02 '22 14:10

rrauenza