Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
What system are you using? FreeBSD's sh has the LINENO variable, so it certainly exists in some places... –  D_Bye Sep 28 '12 at 16:32
    
Neither Ubuntu 12.04 nor Mint 13 seem to have it. –  MMM Sep 28 '12 at 16:36
    
Yes, if sh is a link to bash then it will have most bash features. –  jw013 Sep 28 '12 at 17:21
2  
On ubuntu sh is not bash but dash –  Nahuel Fouilleul Sep 28 '12 at 18:39
4  
You must be confusing with something else. No Linux has ever had a Bourne shell. There now exits ports of the Bourne shell to Linux, since the code of the Bourne shell has been released in the early 2000s, but it's only for historical interest as there's no point using the Bourne shell nowadays. POSIX specifies LINENO, so it should be present in any conforming (to POSIX, UNIX or LSB) "sh" which unfortunately doesn't include "dash" (there's a bug report on that) –  Stéphane Chazelas Sep 28 '12 at 21:30

2 Answers 2

You could post-process your script

awk '{gsub(/[$]LINENO/,FNR);print}' script_template > script

But it usually causes problems with having to maintain the template and generate the script each time you want to make edits.

share|improve this 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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.