Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While executing shell scripts, how to know which line number it's executing,

Tags:

bash

shell

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.

like image 509
anish Avatar asked May 30 '12 09:05

anish


People also ask

How do I show line numbers in Unix shell script?

Press the Esc key if you are currently in insert or append mode. Press : (the colon). The cursor should reappear at the lower left corner of the screen next to a : prompt. A column of sequential line numbers will then appear at the left side of the screen.

How do I show line numbers in bash?

In Bash, $LINENO contains the line number where the script currently executing. If you need to know the line number where the function was called, try $BASH_LINENO . Note that this variable is an array.

How do I read a specific line in a shell script?

Using the head and tail Commands Let's say we want to read line X. The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.


2 Answers

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
like image 64
Charles Duffy Avatar answered Oct 14 '22 03:10

Charles Duffy


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

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

Demo:

$ ./lineno
2
3
4
like image 33
Dennis Williamson Avatar answered Oct 14 '22 01:10

Dennis Williamson