Different Shell Script Loops
1. if
Conditional binary structure: depending on whether a condition is true or false, we execute a block or we don’t.
|
|
If the condition is true, then instruction (which can be a block of instructions) is executed.
|
|
For the same construction but with multiple conditions:
|
|
If the condition is true, then instruction1 is executed and the second is ignored, otherwise instruction2 is executed and the first is ignored.
|
|
elif is equivalent to else if. Thus instruction2 is only executed if condition1 and condition2 are both true at the same time.
2. for
Repetitive bounded structure: loop for which we know the total number of iterations before the first pass.
|
|
We therefore vary the variable by making it take all the values of the set successively.
3. while
Repetitive structure as long as the condition is true.
|
|
Loop whose instructions are executed as long as the condition expression is true.
Example:
|
|
or
|
|
4. until
Repetitive structure until the condition is true (i.e. as long as it is false).
|
|
Loop whose instructions are executed as long as the condition expression is false.
5. case
Multiple choice conditional structure: depending on the value of the string expression, we can execute a wide range of instructions.
|
|
If the string is similar to pattern_1 (which is a path expansion string, accepts meta characters * ?, [], {} and ~) then instruction1 is executed.
The string can perfectly verify several different patterns simultaneously, in this case the corresponding instructions (or blocks of instructions) will all be executed.
6. Tests
The conditions of the structures can be evaluated using the test command.
6.1 String Tests
|
|
Returns true if string is empty.
|
|
Returns true if string is not empty.
|
|
Returns true if the two strings are equal.
|
|
Returns true if the two strings are not equal.
6.2 Numeric Tests
|
|
Returns true if strings string_1 and string_2 are in the relational order defined by the operator which can be one among those in the table below.
Operator | Meaning |
---|---|
-eq | = |
-ne | <> |
-lt | < |
-le | <= |
-gt | > |
-ge | >= |
6.3 File Tests
|
|
Returns true if the file meets the condition which can be one among those described in the table below.
Operator | Returns true if |
---|---|
-p | it’s a named pipe |
-f | regular file |
-d | directory |
-c | special file in character mode |
-b | special file in block mode |
-r | read access |
-w | write access |
-x | execution access |
-s | non-empty file |
6.4 Other Operators
It is possible to combine tests by using parentheses and the boolean operators of the following table:
Operator | Meaning |
---|---|
! | negation |
-a | conjunction (and) |
-o | disjunction (or) |
Last updated 21 Oct 2008, 15:22 CEST.