获取 Bourne shell 脚本中的行号

MMM*_*MMM 6 shell dash shell-script

我希望能够在 shell 脚本中打印当前行号。我知道$LINENOBash shell 中的变量,但它似乎不存在于 Bourne shell 中。有没有其他变量或方法可以获得行号?

Gil*_*il' 2

LINENO是 ksh 的一项功能,也存在于 bash 和 zsh 中。Bourne shell、POSIX 规范或 dash 中没有这样的功能。如果您需要行号,请确保您的脚本在具有该功能的 shell 下执行。大多数系统都提供 bash 或 ksh。

if [ -z "$LINENO" ]; then
  if type ksh >/dev/null 2>/dev/null; then
    exec ksh "$0" "$@"
  elif type bash >/dev/null 2>/dev/null; then
    exec ksh "$0" "$@"
  else
     echo 1>&2 "$0: Fatal error: unable to find a shell that supports LINENO."
     exit 100
  fi
fi
Run Code Online (Sandbox Code Playgroud)