Omroth
Omroth

Reputation: 1119

$BASH_COMMAND is overwritten too early in Trap DEBUG

I have

trap 'python my_script.py --command \"$BASH_COMMAND\"' DEBUG

my_script.py is

from argparse import ArgumentParser
parser = ArgumentParser()

parser.add_argument('--command', default="")
args = parser.parse_args()

command = args.command

print("COMMAND", command)

But when I run a bash command the output is

PROMPT_COMMAND='python my_script.py'

Rather than the command that was run that triggered the trap.

How can I get the initial run command from my_script.py?

Upvotes: 0

Views: 315

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

BASH_COMMAND is currently executed command. So as you found out, the current program at python my_script.py is that script and that's what is in BASH_COMMAND.

Cache the current value of BASH_COMMAND and execute your script for the previous value that was in BASH_COMMAND. From Echoing the last command run in Bash? .

trap 'prev_bash_command=$BASH_COMMAND; python my_script.py --command \"$prev_bash_command\"' DEBUG

Upvotes: 4

Related Questions