how to exit a while true loop

Hi guys,

I'm new to unix but loving it!! BUT this is driving me nuts as i can't work out the best way to do it.

I have a while true loop that i use to monitor something. For my own reasons in ths script i have disabled the CTRL C using the trap command. But i want to put in a option to exit the script using the exit command.

So i get it to display the info for say 30 seconds then it loops, then displays the new info. While it is waiting for 30 seconds i want the option to exit the script by pressing say the x key. As im new to unix not sure how to do this, i either work in ksh or bash. Pleeease give me an idea how to do this. :o

Hm, want to quit but trap the Ctrl-C.

Fortunately their is a SIGQUIT signal you could use. (Normally ctrl+\)

Been told that im not allowed to use the CTRL C to exit the scripts, so i removed the option. (Don't ask me why but the admin was suggesting it caused issues) I want to press any key while the loop is running to exit. So the script is running the loop but also looking for a key press to exit, tried exiting the script using CTRL \ didnt work. IF SIGQUIT is an answer how can i use it in the way i want?

#! /usr/local/bin/bash
count=0
while : ; do
        echo count = $count
        ((count=count+1))
        read -t 10 && break
done
echo exited while loop
exit 0

This uses the -t option to the read command in bash. The "count" is just to have something that changes to display with each iteration. If the user presses return within 10 seconds, the read succeeds, otherwise it fails. (If it succeeds, we just discard the data that was read since no variable is used with the read.) -t works with bash, but most versions of ksh do not have it.

#you can use break to quit the loop.
#you can quit the script itself by using exit once you reach the condition to quit the whole!!

If you want to run it for particular time in seconds... here we go
#!/bin/sh
secs=$1
start=`date +%s`
end=$((start+$secs))
while : ; do
if [ `date +%s`-eq $end ]; then
break
fi
.
.
. here goes your monitoring logic
done
#here you can write the rest of the script or simply put exit 0

---------now you can run the script passing the arguement as no. of secs you want ti to run!!

-ilan

Thanks guy for the advice i ended up using.....

answer="No";read -p "Do you want to exit? Answer y to exit. " -t 30 answer;echo " Your answer is $answer";
if [ "$answer" = "y" ];then
echo "you have chosen to exit."
break
else
echo ""

giving them a 30 second window to exit the script or the while true just continues.. works a treat.