Reputation: 59
I am very new to shell scripting and need help in this.
I would like to run some commands with infinite loop and I want the loop to be terminated on ctrl-c is pressed, but before terminate I want current iteration to be completed (means all the statements within the loop should be executed.
infinite-loop (
command 1;
command 2;
command 3;
loop-ends
so on ctrl-c at any point in execution, all 3 commands should be executed before the loops is terminated. loops should continue to execute if ctrl-c is not pressed.
any suggestion please??
Upvotes: 1
Views: 225
Reputation: 207465
Like this (untested)
#!/bin/bash
trap "DONE=1" SIGINT
DONE=0
while [ $DONE -eq 0 ]
do
process1
process2
process3
done
Upvotes: 1
Reputation: 8429
You can use trap
to trap the SIGINT signal. (tested)
#!/bin/sh
trap ctrl_c INT
ctrl_c () {
RUNNING=0
}
RUNNING=1
while [ "$RUNNING" = 1 ]; do
echo 'working'
sleep 1
echo 'on something else'
sleep 1
echo 'done'
done
Upvotes: 3