Is there a way to run one command before any terminal command gets executed?

For example:

> ls -ltr
> "Hello you ran ls -ltr" //this is what I would like to achieve
> ..output of ls -ltr will be here

Is it possible to run make sure an echo runs before any command is executed?


marked as duplicate by muru, jimmij, garethTheRed, cuonglm bash Feb 5 '16 at 7:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • You have just described xtrace. PS4='Hello, you ran: '; set -x – mikeserv Feb 5 '16 at 2:46

You might want to look into setting a DEBUG trap, which allows you to set up what is effectively a pre-exec hook in a manner similar to zsh. See https://superuser.com/questions/175799/does-bash-have-a-hook-that-is-run-before-executing-a-command.

  • Awesome, exactly what I am looking for - cheers. – mixiul__ Feb 4 '16 at 18:04
  • Glad to have helped! – DopeGhoti Feb 4 '16 at 18:22

Bash has the concept of assigning a function to ps1 so mine looks like

export PROMPT_COMMAND='PS1=$(make_ps1); set_xterm_title'

where make_ps1 is

    if [ $? = 0 ];then
        echo '\[\e[${host_color}m\][\D{%F %T} \u@\h \W]\[\e[0m\]\n\$ '
        echo '\[\e[7m\e[${host_color}m\][\D{%F %T} \u@\h \W]\[\e[0m\]\n\$ '

you should be able to leverage that to do whatever you want, but it will run after the command is executed so this might not work for what you need.

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