3

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?

3
  • you mean how you can do an if/else statement inside the while ? I dont understand Commented Nov 3, 2011 at 20:03
  • 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. Commented Nov 3, 2011 at 20:08
  • @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. Commented Nov 3, 2011 at 21:13

3 Answers 3

7
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).
Sign up to request clarification or add additional context in comments.

1 Comment

I bet he's not asking that... I don't understand why he says: "What I want to do is loop the entire script"
0

An if in bash is just: if [ some test ]; then some_command; fi:

while [ 1 ]
do
    if [ some test ]
    then
        some command
    else
        other cmd
    fi
sleep 10
done

Bash Scripting Guide

1 Comment

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.
0

Correction to chown case added brake to finish the loop Corrected

while [ 1 ]
do
    if [ some test ]
    then
        some command
    brake
    else
        other cmd
    fi
sleep 10
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.