Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

Thanks

share|improve this question

marked as duplicate by muru, jimmij, garethTheRed, cuonglm bash Feb 5 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 at 2:46
up vote 9 down vote accepted

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 http://superuser.com/questions/175799/does-bash-have-a-hook-that-is-run-before-executing-a-command.

share|improve this answer
    
Awesome, exactly what I am looking for - cheers. – mixiul__ Feb 4 at 18:04
    
Glad to have helped! – DopeGhoti Feb 4 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

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

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.

share|improve this answer

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