Execute Command After Every Command in Bash

Execute command after every command in bash

To execute a cmd before every command entered, set a trap on DEBUG. Eg.

trap date DEBUG

To execute that command before emitting a prompt, set PROMPT_COMMAND:

PROMPT_COMMAND=date

Run command after all bash commands automatically?

Found out you can do this by setting the PROMPT_COMMAND variable. In my bashrc, I added this line: export PROMPT_COMMAND='alert'.

How to run some command before or after every Bash command entered from console?

As l0b0 suggests, you can use PROMPT_COMMAND to do your second request and you won't have to touch PS1.

To do your first request, you can trap the DEBUG pseudo-signal:

trap 'echo "foobar"' DEBUG

Pass every command executed in the bash shell to a variable

You can use this to get current command :

HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//"

This is what I use to display current command on xterm title :

PS0='$(printf "\e]0;%s\7" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'

In your case, you can do (update after comments):

PS0='$(printf "\033k%s\033" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'

or

PS0='$(printf "\033k%s\033\\\\" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'

Execute function every n commands in bash

You can trap DEBUG signal in shell with a custom function.

runcmd() { if (( n==5 )); then n=0; pwd; else ((n++)); fi; }

trap 'runcmd' DEBUG

Change pwd with your custom command or script.

  • trap 'handler' DEBUG calls handler after running every command in shell but won't call runcmd when just enter is pressed in shell.

Edit: Thanks to @kojro: you can shorten this function as:

runcmd() { (( n++ % 5 )) || pwd; }


Related Topics



Leave a reply



Submit