📜  for while bash - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:30:50.370000             🧑  作者: Mango

Shell Scripting with For and While Loops

If you're a programmer, you know that looping constructs are an essential tool in your arsenal. In Shell Scripting, we use for and while loops to iterate over a set of instructions repeatedly.

The for Loop

The for loop in Shell Scripting is used to iterate over a set of values. The syntax of a for loop is as follows:

for item in list
do
    # Commands
done

Where item is a variable that represents each item in the list.

Example:

for item in 1 2 3 4 5
do
    echo $item
done

Output:

1
2
3
4
5

In the example above, we iterate over a list of values (1, 2, 3, 4, and 5) and for each item in the list, we print its value.

The while Loop

The while loop in Shell Scripting is used to iterate over commands as long as a specified condition is true. The syntax of a while loop is as follows:

while condition
do
    # Commands
done

Where condition is a Boolean expression that is evaluated before each iteration.

Example:

i=1
while [ $i -le 5 ]
do
    echo $i
    i=$((i+1))
done

Output:

1
2
3
4
5

In the example above, we use a while loop to iterate over a set of commands until the value of i reaches 5. The condition in the while loop is [ $i -le 5 ], which is true as long as the value of i is less than or equal to 5.

Conclusion

Loops are an essential tool in Shell Scripting, and for and while loops are two of the most common looping constructs. With these constructs, you can iterate over a set of values or execute commands as long as a specified condition is true.