Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function every n commands in bash

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?

like image 640
carpedm20 Avatar asked Dec 25 '22 23:12

carpedm20


2 Answers

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; }
like image 50
anubhava Avatar answered Jan 07 '23 21:01

anubhava


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.

like image 25
Wintermute Avatar answered Jan 07 '23 20:01

Wintermute