Reputation: 8128
I have a bash script where I trap errors using the trap command, and I would like to be able to print the name of the last command (the one that failed)
#!/bin/bash
function error
{
# echo program name
}
trap error ERR
# Some commands ...
/bin/false foo # For testing
I'm not sure what to put in the error
function. I tried echo $_
but that only works if the command has no arguments. I also tried with !!
but that gives me "!!: command not found". At an interactive prompt (also bash) I get:
$ /bin/false foo
$ !!
/bin/false foo
which seems to be pretty much what I want. Why the difference? What is the easiest way to get the name of the previous command inside a script?
Upvotes: 4
Views: 886
Reputation: 360005
Try echo $BASH_COMMAND
in your trap function.
From man bash
:
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.
Upvotes: 4
Reputation: 2779
You need to set
set -o history
to quote bash manual page:
When the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. The text of the last HISTSIZE commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expansion (see EXPANSION above) but after history expansion is performed, subject to the values of the shell variables HISTIGNORE and HISTCONTROL.
In general, read the HISTORY and HISTORY EXPANSION sections in bash man page.
Upvotes: 2