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?
Asked
Active
Viewed 2,835 times
6
jasonwryan
- 71,734
- 34
- 193
- 226
MMM
- 133
- 1
- 4
-
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
-
2On ubuntu sh is not bash but dash – Nahuel Fouilleul Sep 28 '12 at 18:39
-
6You 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
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
Gilles 'SO- stop being evil'
- 807,993
- 194
- 1,674
- 2,175
1
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.
Paddy3118
- 295
- 1
- 6
-
Thanks for the idea! The script postprocessing could also be integrated into some `sh` wrapper! – saulius2 Aug 31 '23 at 10:13