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,852 times
6

jasonwryan
- 73,126

MMM
- 143
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'
- 829,060
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
-
Thanks for the idea! The script postprocessing could also be integrated into some
sh
wrapper! – saulius2 Aug 31 '23 at 10:13
sh
has theLINENO
variable, so it certainly exists in some places... – D_Bye Sep 28 '12 at 16:32sh
is a link tobash
then it will have mostbash
features. – jw013 Sep 28 '12 at 17:21