1

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?

5
  • At what event do you want to trigger trap ? Commented Nov 7, 2013 at 15:12
  • @thom I thought I was clear: echo "hi" Commented Nov 7, 2013 at 15:14
  • 1
    grep -n "echo" myscript.sh? Commented Nov 7, 2013 at 15:17
  • Trap doesn't work that way. It reacts on signals emitted by the OS or an external program. You can, however, do something like kill -SIGUSR1 $$ and your trap would be trap 'echo_report $LINENO' SIGUSR1 Commented Nov 7, 2013 at 15:19
  • You can use the DEBUG signal, but that is non-selective; it is triggered by (just about) every command, not just, say, echo commands. Commented Nov 7, 2013 at 15:30

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Why command echo and not builtin echo or even use printf? Do you really like the external command echo?
command doesn't force external. It just ignores functions. See gnu.org/software/bash/manual/bashref.html#Bash-Builtins

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.