Shell – Get line number in a Bourne shell script

dashshellshell-script

I'd like to be able to print the current line number in a shell script. I know about the $LINENO variable in Bash shells, but it doesn't seem to exist in Bourne shells. Is there any other variable or way I can get the line number?

Best Answer

LINENO is a ksh feature, also present in bash and zsh. There is no such feature in the Bourne shell, in the POSIX specification or in dash. If you need the line number, make sure that your script is executed under a shell that has the feature. Most systems have either bash or ksh available.

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
Related Question