for-in loop
The for-in statement is designed to sequentially access values listed in a list. Each value in the list is sequentially assigned to a variable. The syntax is as follows:
for переменная in список_значений do команды done
Let's consider a small example:
#!/bin/bash for i in 0 1 2 3 4 #переменной $i будем поочередно присваивать значения от 0 до 4 включительно do echo "Console number is $i" >> /dev/pts/$i #Пишем в файл /dev/pts/$i(файл виртуального терминала) строку "Console number is $i" done #цикл окончен exit 0
After executing the example, a line with its number will appear in the first 5 virtual consoles (terminals). The variable $i is sequentially assigned values from the list, and the loop operates on the value of this variable.
Loops. while loop
The while loop is more complex than the for-in loop and is used to repeat commands as long as a certain expression is true (return code = 0). The syntax of the statement is as follows:
while выражение или команда возвращающая код возврата do команды done
Let's consider an example of the loop's operation:
#!/bin/bash again=yes #присваиваем значение "yes" переменной again while [ "$again" = "yes" ] #Будем выполнять цикл, пока $again будет равно "yes" do echo "Please enter a name:" read name echo "The name you entered is $name" echo "Do you wish to continue?" read again done echo "Bye-Bye"
