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
  1. 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 in if and while is arbitrary command whose exit status (zero = true, nonzero = false) is used as the condition value and [ is just alias for special test command (both built-in in most shells, but they don't have to be).
  2. Any shell construct is allowed between do/done including conditionals, more loops and cases.
  3. Use break to terminate innermost loop from inside (just like most other languages).
Share:
15,239
bikerben
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, 2022

Comments

  • bikerben
    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
      webbi about 12 years
      you mean how you can do an if/else statement inside the while ? I dont understand
    • bikerben
      bikerben about 12 years
      Yes 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
      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 the trap command.
  • Jan Hudec
    Jan Hudec about 12 years
    No. 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 where test is not enough and end up going with expr.
  • webbi
    webbi about 12 years
    I bet he's not asking that... I don't understand why he says: "What I want to do is loop the entire script"
  • bikerben
    bikerben about 12 years
    This was just what I was looking for. Thank you very much.