当
在bash shell中进行复制/粘贴
grep -c
返回0
时,脚本为什么会以“-1”退出代码失败。只有在设置了set -o errexit
时才会发生这种情况。在bash shell中进行复制/粘贴
cat <<'EOT' > /tmp/foo.sh
#!/usr/bin/env bash
function bash_traceback() {
local lasterr="$?"
set +o xtrace
local code="-1"
local bash_command=${BASH_COMMAND}
echo "Error in ${BASH_SOURCE[1]}:${BASH_LINENO[0]} ('$bash_command' exited with status $lasterr)"
if [ ${#FUNCNAME[@]} -gt 2 ]; then
# Print out the stack trace described by $function_stack
echo "Traceback of ${BASH_SOURCE[1]} (most recent call last):"
for ((i=0; i < ${#FUNCNAME[@]} - 1; i++)); do
local funcname="${FUNCNAME[$i]}"
[ "$i" -eq "0" ] && funcname=$bash_command
echo -e " $i: ${BASH_SOURCE[$i+1]}:${BASH_LINENO[$i]}\t$funcname"
done
fi
echo "Exiting with status ${code}"
exit "${code}"
}
test_redirecting_of_stdout_stderr() {
# Exit program when error found
set -o errexit
# Exit program when undefined variable is being used
set -o nounset
local up_count
up_count=$(ls | grep -c NOTHING_MATCHED)
echo "up_count: $up_count"
}
# provide an error handler whenever a command exits nonzero
trap 'bash_traceback' ERR
set -o errtrace
test_redirecting_of_stdout_stderr
EOT
bash /tmp/foo.sh
输出
debian:~/my-mediawiki-docker$ bash /tmp/foo.sh
Error in /tmp/foo.sh:31 ('up_count=$(ls | grep -c NOTHING_MATCHED)' exited with status 255)
Traceback of /tmp/foo.sh (most recent call last):
0: /tmp/foo.sh:31 up_count=$(ls | grep -c NOTHING_MATCHED)
1: /tmp/foo.sh:40 test_redirecting_of_stdout_stderr
Exiting with status -1
debian:~/my-mediawiki-docker$
printf ' %s: %s:%s\t%s\n' "$i" "${BASH_SOURCE[$i+1]}" "${BASH_LINENO[$i]}" "$funcname"
而不是echo -e
,则可以更可靠地在更广泛的有效 bash 运行时配置中工作。) - Charles Duffy