Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show the line number in Shell (/bin/sh) script when debugging (-x)?

Tags:

linux

shell

unix

sh

I'm debuging a script in DASH SHELL by using #!/bin/sh -x and I would like to show the script line number when debugging.

Already tryied changing PS4 variable (as showed in this answer), without success because it only works in bash, I need shell.

PS4='Line ${LINENO}: '

I expect the following output:

123: + echo test

But there is nothing in $LINENO in shell.

I'm using ubuntu 16.04 x64 and dash version 0.5.8-2.1ubuntu2 500

Specifically I'm trying to debug the Virtualbox configure file for building it on linux. Here are some parts of the script and how I tryied.

 #!/bin/sh -x
PS4='Line ${LINENO}: '
LC_ALL=C
export LC_ALL

# append some extra paths
PATH="$PATH:/opt/gnome/bin"
# Solaris (order of paths important for tr, grep, sed to work)
PATH="/usr/xpg4/bin:$PATH:/usr/local/bin:/usr/sfw/bin:/usr/ccs/bin"
ORGPATH=$PATH
...
    echo "  disabled hardening!"
    echo "  +++ WARNING +++ WARNING +++ WARNING +++ WARNING +++ WARNING +++ WARNING +++"
    echo ""
fi
echo "Enjoy!"
cleanup

the results are:

Line : [ 1 -ne 0 ]
Line : test -z nofatal
Line : echo
Line : echo
Line : return 1
like image 473
Sunfloro Avatar asked Nov 26 '25 19:11

Sunfloro


1 Answers

All the functionality discussed here is already required in the User Portability Utilities annex to the POSIX standard.

Moreover, dash, the most common non-bash /bin/sh implementation on Linux, already has the functionality built-in, as you can test below:

dash -s <<'EOF'
PS4=':$LINENO+'; set -x
echo "First line"
echo "Second line"
EOF

...correctly emits (with dash 0.5.10.2):

:2+echo First line
First line
:3+echo Second line
Second line
like image 106
Charles Duffy Avatar answered Nov 29 '25 10:11

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!