oaugustopro
oaugustopro

Reputation: 790

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

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

Upvotes: 3

Views: 2286

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295281

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

Upvotes: 3

Related Questions