简体   繁体   中英

How to display last command that failed when using bash set -e?

I am using set -e to stop execution of a script on first error.

The problem is that this does not tell me what went wrong.

How can update a bash script so it will display me the last command that failed?

Instead of set -e , use an ERR trap; you can pass $BASH_LINENO in to get the specific line number on which the error occurred. I provide a script taking advantage of this in my answer at https://stackoverflow.com/a/185900/14122

To summarize:

error() {
   local sourcefile=$1
   local lineno=$2
   # ...logic for reporting an error at line $lineno
   #    of file $sourcefile goes here...
}
trap 'error "${BASH_SOURCE}" "${LINENO}"' ERR

您尝试过--verbose吗?

bash --verbose script.sh
  1. make err.sh

     set -e trap 'echo "ERROR: $BASH_SOURCE:$LINENO $BASH_COMMAND" >&2' ERR 
  2. include it ( . err.sh ) in all your scripts.

  3. replace any

    ... | while read X ; do ... ; done

    with

    while read X ; do ... ; done < <( ... )

    in your scripts for the trap to give the correct line number/command in the error message

You can't use set -e by itself because processing will immediately stop after any error. Take a look at the Set Builtin section of the Bash Reference Manual for more information about the -x and -v options, which you can use for debugging.

Something like:

set -e
set -v

will exit on any error, while showing you each input line as it is read. It will not, however, show you just the line with the error. For that, you will need to do your own explicit error checking.

For example:

set +e
if false; then
    real_exit_status=$?
    echo 'Some useful error message.' >&2
    exit $real_exit_status
fi

set -ex将在执行时显示(所有)行,并在返回非零的第一条命令处停止(不作为if/while/until构造的一部分)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM