I'd like to make a program which will be executed every n commands in bash. For example, I want user to answer for a question for every 5 commands in bash.
I think this function can be implemented using only bash script, be I couldn't find a proper solution for this. I don't want to compile a new bash and I think this can be done by a bash script. If so, do I have to change bashrc?
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; }
You could use the PROMPT_COMMAND
shell variable to run a command after every user command (every time the prompt is displayed) and use a counter in that to get something to execute every fifth time:
PROMPT_COMMAND="if [ \"\$HELLO_COUNTER\" -le 0 ]; then HELLO_COUNTER=5; echo 'Hello, world.'; else let --CTR; fi"
EDIT: @kojiro has a good idea in the comments to use the builtin LINENO
variable instead of a new counter, as in
PROMPT_COMMAND='(( LINENO % 5 )) || echo "Hello world."'
I like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With