0

I created two traps

trap function1 DEBUG
trap pwd ERR
function function1 {
echo $BASH_COMMAND
}

If I use some wrong command let's say a, then output is->

a
bash: a: command not found
a
/home/user/dir

So second time DEBUG is called to execute pwd, but why $BASH_COMMAND is still a? Is there any way to know in the function1 that this call to function is made while executing command in trap ERR?

EDIT

Two traps are

trap -- 'f' DEBUG
trap -- 's' ERR
function f 
{ 
    echo "inside function f command is $BASH_COMMAND"
}
function s 
{ 
    echo "inside function s command is $BASH_COMMAND"
}

Output for wrong command a, is

inside function f command is a
bash: a: command not found
inside function f command is a
inside function s command is echo "inside function s command is $BASH_COMMAND"

The second inside function f command is a, must be from ERR trap.

1 Answer 1

1

This can be found in the bash documentation (see your man bash), where it writes in several places about various aspects of trap.

BASH_COMMAND The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.

and also

the DEBUG and RETURN traps [...] are not inherited unless the function has been given the trace attribute [...] or the -o functrace shell option has been enabled with the set builtin (in which case all functions inherit the DEBUG and RETURN traps)

If you modify your trap commands slightly you can see this more clearly

trap 'echo "##DEBUG## $BASH_COMMAND"' DEBUG
trap 'echo "##ERR## $PWD"' ERR

a
##DEBUG## a
-bash: a: command not found
##DEBUG## a
##ERR## /home/roaima

and

f() { printf "%s..." "We are in function f()"; sleep 1; printf " OK\n";  }
f
##DEBUG## f
We are in function f()... OK
7
  • Got it, but I wasn't able to stop commands in ERR, to go inside DEBUG. If it's not able to possible, then can I identify those commands.
    – Prvt_Yadav
    Jan 27, 2021 at 11:42
  • You want to debug the commands inside the ERR trap function? Then set -o functrace and set -o errtrace. It's all in the man page Jan 27, 2021 at 12:39
  • Well opposite of that, I don't want to DEBUG commands in ERR trap.
    – Prvt_Yadav
    Jan 27, 2021 at 14:52
  • I don't see DEBUG commands in the ERR trap. Perhaps you've changed the default settings for your bash session Jan 27, 2021 at 14:57
  • 1
    Hi, can you quickly check the edit, just want to make sure, we are on same page.
    – Prvt_Yadav
    Jan 27, 2021 at 15:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .