如何在Bash中捕获错误坏数组下标

时间:2018-03-20 15:23:10

标签: bash error-handling

此代码段会产生两个错误:"找不到命令"被陷阱困住的"坏数组下标"那不是。有没有办法陷阱"坏数组下标?"

运行Bash版本4.4

shopt -s extdebug  # Necessary after 4.3 for trapping in functions
set -o pipefail
set -o errtrace

error() {
    echo "There was an error at line $1"
}
trap 'error ${LINENO}' ERR

declare -A arr
foo=''
# Next line generates one error:
# -bash: arr: bad array subscript  # this error is not trapped
"${arr[$foo]-echo}"

# Next line generates two errors:
# -bash: arr: bad array subscript  # this error is not trapped
# -bash: : command not found  # this error is trapped
"${arr[$foo]}"
:

0 个答案:

没有答案