Execute a function for every n commands in bash

I would like to create a program that will be executed every n commands in bash. For example, I want the user to answer a question for every 5 commands in bash.

I think this function can only be implemented using a bash script, I could not find a suitable solution for this. I do not want to compile the new bash, and I think it can be done with a bash script. If so, do I need to change bashrc?

+4
source share
2 answers

You can capture the DEBUGsignal in the shell using a custom function.

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

trap 'runcmd' DEBUG

Change pwdto your custom command or script.

  • trap 'handler' DEBUG handler , runcmd, .

: @kojro: :

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

PROMPT_COMMAND ( , ) , - :

PROMPT_COMMAND="if [ \"\$HELLO_COUNTER\" -le 0 ]; then HELLO_COUNTER=5; echo 'Hello, world.'; else let --CTR; fi"

EDIT: @kojiro LINENO ,

PROMPT_COMMAND='(( LINENO % 5 )) || echo "Hello world."'

.

+3

All Articles