Run the bash script every time when command lines are executed

I am a new Ubuntu/Linux user, I would like to ask a question as my title above.

For example, I have a bash file ./script, I would like to make it run automatically when I type any command line. Once I execute command line pwd then the ./script will be executed. Once I type the next command line ls -la then the ./script will be executed again.


Solution 1:

You need to set PROMPT_COMMAND variable. From man bash:

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

For example, this will write current date into /tmp/PC every time a command is executed:

 $ PROMPT_COMMAND="date > /tmp/PC"

Solution 2:

You are looking for PROMPT_COMMAND environment variable, the value of this variable will be executed as command, after each command given in the terminal is executed, just before showing the next prompt.

For example, set it as:

export PROMPT_COMMAND='/path/to/script'

Make the script, /path/to/script, executable first.

Now the script will be run after each command.

Just to note, if you don't want the variable to be exported i.e. make it a shell variable instead of a environment one, drop export:

PROMPT_COMMAND='/path/to/script'

From man bash:

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