16

While executing shell scripts, how to know which line number it's executing, do have write a wrapper , where i can execute a shell scripts from a shell scripts and to know which line number it's executing.

3 Answers 3

22

You can set the PS4 variable to cause set -x output to include the line number:

PS4=':${LINENO}+' set -x 

This will put the line number before each line as it executes:

:4+command here :5+other command 

It's important to have some sigil character (such as a + in my examples) after your variable expansions in PS4, because that last character is repeated to show nesting depth. That is, if you call a function, and that function invokes a command, the output from set -x will report it like so:

:3+++command run within a function called from a function :8++command run within a function :19+line after the function was called 

If multiple files are involved in running your script, you might want to include the BASH_SOURCE variable as opposed to only LINENO (assuming this really is a bash script, as opposed to /bin/sh -- be sure your script starts with #!/bin/bash!):

PS4=':${BASH_SOURCE}:${LINENO}+' set -x 
Sign up to request clarification or add additional context in comments.

3 Comments

You said "the last character is repeated to show nesting depth", but man bash instead says "The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection."
What do you understand "levels of indirection" to mean in this context? Describing stack-frame depth in that way is indeed not the most direct bit of nomenclature, but it is nonetheless the meaning at hand.
@LucianWischik, ...see also wiki.bash-hackers.org/scripting/…
6

Bash has a special variable $LINENO which does what you want.

#!/bin/bash echo "$LINENO" echo "$LINENO" echo "$LINENO" 

Demo:

$ ./lineno 2 3 4 

Comments

5
#!/bin/sh -x 

will report the lines as they're executed (the -x option, to be clear). It won't give you the line number, but report the actual line.

An alternative, but more painful, approach is to use a trap handler, as documented here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.