Radu Rădeanu
Radu Rădeanu

Reputation: 2722

Find the line number where an echo appear in a bash script

It is possible to make the following bash script to work as I said in the title?

#!/bin/bash

echo_report() {
    echo "echo on line $1"
}

trap 'echo_report $LINENO' [sigspec]

#same code here

echo "hi"

#more code here

I don't know what should I use for [sigspec]...

If using trap is not possible, what other options do I have?

Upvotes: 1

Views: 336

Answers (1)

Aron Griffis
Aron Griffis

Reputation: 1729

Wrap echo in a function, then use caller to display the line number:

#!/bin/bash

echo() {
    caller
    command echo "$@"
}

echo "hi"

Result:

$ bash foo.bash
8 foo.bash
hi

Upvotes: 6

Related Questions