Sample Header Ad - 728x90

Run a command after interrupting while loop with Ctrl-C in bash one-liner?

0 votes
1 answer
421 views
In the below one-liner, I run an "infinite" while loop which prints some numbers:
$ bash -c 'trap stopit SIGINT; run=1; stopit() { run=0; }; while [ $run ]; do for i in {0..4}; do v=$(($i*50)); d=$(for ((k=0;k<=(5+$i);k++)); do echo -n $(($v*(($k+$i)%2))),; done); d=${d%?}; c=$(echo numbers $d); echo $c; sleep 0.1; done; done ; echo Done'
numbers 0,0,0,0,0,0
numbers 50,0,50,0,50,0,50
numbers 0,100,0,100,0,100,0,100
numbers 150,0,150,0,150,0,150,0,150
numbers 0,200,0,200,0,200,0,200,0,200
numbers 0,0,0,0,0,0
numbers 50,0,50,0,50,0,50
numbers 0,100,0,100,0,100,0,100
...
... and the "expanded" script is:
trap stopit SIGINT; 
run=1; 
stopit() { 
  run=0; 
}; 
while [ $run ]; do 
  for i in {0..4}; do 
    v=$(($i*50)); 
    d=$(for ((k=0;k<=(5+$i);k++)); do echo -n $(($v*(($k+$i)%2))),; done); 
    d=${d%?}; # cut final comma
    c=$(echo numbers $d); 
    echo $c; 
    sleep 0.1; 
  done; 
done ; 
echo Done
The idea is that the while loop runs "forever" and prints (running task), and once you get bored, you stop it by pressing Ctrl-C. However, what I want, is to print a message *after* Ctrl-C has interrupted the while loop - in the above example, that is the echo Done command. In the above example, I hoped that Ctrl-C would set the run variable to 0, thereby making the loop exit "cleanly" which would then print the command and exit. Unfortunately, when I press Ctrl-C nothing happens, that is, loop keeps on going and then I have to explcitly kill it. How can I make the above script/one-liner exit the while loop on Ctrl-C, and print the final message?
Asked by sdbbs (578 rep)
Mar 29, 2023, 05:54 AM
Last activity: Mar 29, 2023, 06:11 AM