在 shell 脚本中可移植地捕获 ERR

Portably trapping ERR in shell script

我正在尝试编写一个 shell 脚本,该脚本在命令失败时中止并显示有问题的行号。

set -e
trap 'echo "[=11=] FAILED at line ${LINENO}"' ERR

事实证明,陷阱行不适用于 Ubuntu 的默认 shell 脚本解释器 dash。如果我将 shebang 行更改为 #!/bin/bash 这有效但不适用于 #!/bin/sh。有没有办法在不依赖 bash 在场的情况下完成这项工作?

顺便说一下,我从 dash 得到的错误是这样的:

trap: ERR: bad trap

According to various sources on the internets, ERR is not standard at all and only supported by the Korn Shell - which seemed to invent it - and Bash, which seemed to adopt it. https://github.com/bmizerany/roundup/issues/25#issuecomment-10978764

我会选择简单的解决方案。

简单改变

#!/bin/sh

#!/bin/bash

或更好

#!/usr/bin/env bash

您可以像这样在退出时捕获并测试退出代码:

set -e
trap '[ $? -eq 0 ] && exit 0 || echo "[=10=] FAILED at line ${LINENO}"' EXIT