BASH Shell Infinite loop with IF ELSE Statment
15,239
while :; do
if cond1; then
whatever
elif cond2; then
something else
else
break
fi
done
- You do infinite loop using
while true
or using true's shorter alias:
.[ 1 ]
is needlessly complicated and is not what you think it is ([ 0 ]
is also true!). Remember, the condition inif
andwhile
is arbitrary command whose exit status (zero = true, nonzero = false) is used as the condition value and[
is just alias for specialtest
command (both built-in in most shells, but they don't have to be). - Any shell construct is allowed between
do
/done
including conditionals, more loops and cases. - Use
break
to terminate innermost loop from inside (just like most other languages).
Author by
bikerben
I’m Parker Software’s ThinkAutomation Technical Sales Consultant. With a technical background spanning over 20 years in various areas of the IT industry.
Updated on June 04, 2022Comments
-
bikerben over 1 year
Ok I know I've asked a similar question, I understand how to do an infinate loop:
while [ 1 ] do foo bar then sleep 10 done
But if I want to run some (quite a few) IF ELSE Statements in this loop how would I get the script to carry on looping once they had completed how would I go about this?
-
webbi about 12 yearsyou mean how you can do an if/else statement inside the while ? I dont understand
-
bikerben about 12 yearsYes thats it, I have have pretty big script with a fair few if else statements in it. What I want to do is loop the entire script.
-
Jan Hudec about 12 years@bikerben: Well, just wrap the shell code you want in a
while
/do
/done
. And if you intend to break out of it with Ctrl-C (or any other method of killing it), perhaps have a look at thetrap
command.
-
-
Jan Hudec about 12 yearsNo. if in shell is just
if some test; then some command; fi
. The[
is a command used for comparing values and checking existence of files, but there are many cases where you either need some arbitrary command (which
,grep
, ...) or wheretest
is not enough and end up going withexpr
. -
webbi about 12 yearsI bet he's not asking that... I don't understand why he says: "What I want to do is loop the entire script"
-
bikerben about 12 yearsThis was just what I was looking for. Thank you very much.