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 it possible to call a script in this example named hey.sh after every bash command?

For example you type ls hit enter and ls runs, then hey.sh would run.

You then type cd .. (or any other command), cd runs then hey.sh would run, and so on.

share|improve this question
2  
This is either an X-Y problem or a very odd idea; what are you trying to actually achieve? – jasonwryan Jan 14 at 18:54
    
alias in bash.rc maybe? – moonbutt74 Jan 14 at 18:56
    
@jasonwryan I don't believe it to be an X-Y problem, however I agree it is a bit odd. I was looking for a way to update the PS1 from a script which changes after every command entered, and needed a mechanism to do so. – John Jan 15 at 15:02
up vote 17 down vote accepted
PROMPT_COMMAND+="hey.sh;"

PROMPT_COMMAND If set, the value is executed as a command prior to issuing each primary prompt.


Note: Environment variables vs shell variables

By default, PROMPT_COMMAND is not an environment variable. It's just a shell variable.

Both types of variables are accessed the same way ("$variable*"), but environment variables are inherited by child processes whereas shell variables aren't.

The convention is to capitalize environment variables + shell variables that configure your shell (PROMPT_COMMAND does configure your shell), but keep other types of variables lower case.

In bash, you can do: declare -p to find out whether a variable is exported (=is an environment variable) or not:

$ declare -p PATH
declare -x PATH=... #-x means it's exported
$ declare PROMPT_COMMAND
declare -- PROMPT_COMMAND=... #no -x so just a shell variable
share|improve this answer
2  
@John No. Don't export it. Just set it (or append to it, e.g., as shown above). – PSkocik Jan 14 at 19:07
    
Neat, what about after though? – moonbutt74 Jan 14 at 19:42
2  
@moonbutt74 prior to every command == after every command + at the beginning of your bash session – PSkocik Jan 14 at 19:50
1  
Thanks, i didn't know about that. m – moonbutt74 Jan 14 at 21:05
    
@PSkocik I gotcha I was just curious if that was already an environmental variable, upon a quick echo command I found out it was. This does exactly what I was looking for – John Jan 15 at 14:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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