Amit Chouksey
Amit Chouksey

Reputation: 59

shell script - complete iteration before exiting infinite loop

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

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207465

Like this (untested)

#!/bin/bash
trap "DONE=1" SIGINT
DONE=0
while [ $DONE -eq 0 ]
do
    process1
    process2
    process3
done

Upvotes: 1

Ahmed Al Hafoudh
Ahmed Al Hafoudh

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

Related Questions