Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

While loop with a q to quit 3

Status
Not open for further replies.

vodkadrinker

Technical User
May 16, 2002
163
GB
I want to put a q to quit option on an continuosly looping while loop.

example of the while loop:

while true
do
echo "hello world"
sleep 5
done
 


Add a read statement:
Code:
while true
do
  echo "hello world"
  sleep 5
  read x
  if [[ "$x" == 'q' ]]
  then
    break
  fi
done
[3eyes]

----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Hi

Yes, but that way it will way for input on each [tt]read[/tt]. If you use [tt]bash[/tt], you can substitute the [tt]sleep[/tt] with a [tt]read[/tt]'s -t ( timeout ) option :
Code:
while :; do
  echo 'hello world'
  read -t 5 x
  [[ "$x" == 'q' ]] && break
done

Feherke.
 
Yes sorry LKBrwnDBA probably should have explained it better. Many thanks feherke thats what I was looking for.

VD
 
This was what I was really looking for, just incase anyone has the same problem.

trap "rm -f $tmpfile; exit" 0 1 2 15
 
And what has that trap to do with this "While loop w/a q to quit" question?

I'd go easy on the vodka for a bit ;-)


HTH,

p5wizard
 
but never for looping
even like this ?
trap 'break' 2

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
LOL guys, just thought I'd add it in as an option in case anyone else was trying to do a similar script.

Thanks anyway and appreciate the humour [tongue]

VD
 
Hi

We appreciate when the OP comes back with comment on the solution.

And thinking again, I learned something from this. [medal]

On the next "loop breaking" question I will read, I will certainly remember this case.

Feherke.
 
OK, without any extra coding in the loop, let the user break out with ctrl-C or ctrl-\ or ... Then clean up when s/he does so:

[tt]tmpfile=/tmp/date$$
# # #
# set trap to clean up when user interrupts loop
trap "rm -f $tmpfile; exit" 0 1 2 15
# # #
# infinite loop, break out of it by hitting ctrl-C, by closing session, ...
while true
do
# # #
# stuff that includes $tmpfile creation/modification/...
date >> $tmpfile
sleep 1
done[/tt]

(for completeness sake)


HTH,

p5wizard
 
Thanks p5wizard that's pretty much what I did, yep your right I should have explained it a little clearer but there's good vodka to be drunk and as you can imagine things aren't that clear.
[upsidedown]
[dazed]./ \.[tongue]./\.[rednose]

VD
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top