Is there a way to capture all commands executed in a bash or even better in sh?

I need a wrapper script that gets called everytime a command is executed. Like when I type cd /home/ I want my wrapper script command_wrapper.sh to be called. Inside I want to cancel the command or call another command.


echo "you tried to call the command [$@]"

It also would be okay if the script only gets called when a command doesn't exist. Is this possible?


You can use the DEBUG trap to do this. In this trap, $BASH_COMMAND contains the command last executed.

trap 'echo "you tried to call the command [$BASH_COMMAND]"' DEBUG

Note that, if you are executing commands as part of your prompt or $PROMPT_COMMAND, the trap will run on these as well. You can add checks to see if $BASH_COMMAND is the same as $PROMPT_COMMAND to avoid some of these.

As for executing when the command doesn't exist, in bash, if a function named command_not_found_handle exists, that function is executed any time that a command is not found. It's executed with all of the arguments from the command line you tried to execute passed as arguments, so you can do something like this:

command_not_found_handle() {
    echo "you tried to call the command [$@]"

This results in:

$ foo bar
you tried to call the command [foo bar]
  • Thanks! Working like a charm! But do you know a way to interrupt a command which exists? – bricklore Jul 23 '15 at 16:27
  • @MalteSchmitz I added some information about the DEBUG trap, which might help. :-) – Chris Down Jul 23 '15 at 16:47
  • wow! Thank you very much - that's exactly what I was searching for! :-D – bricklore Jul 23 '15 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.