How to call a script after every bash command

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x