Циклы: `for`, `while`, `until`
Автоматизируйте повторяющиеся задачи, освоив различные типы циклов в скриптах оболочки.
«Циклы: `for`, `while`, `until`» — бесплатный урок Linux Command Line Mastery на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Linux Command Line Mastery, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Linux Command Line Mastery содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Use Loops?
Imagine you need to perform the same action many times, like saying 'Hello' to everyone in a list, or counting from 1 to 100. Doing this manually would be tedious and error-prone.
This is where loops come in! Loops allow your script to repeat a set of commands multiple times, saving you effort and making your scripts more efficient.
Looping Through Items with `for`
The for loop is perfect when you know exactly what items you want to iterate over. It goes through a list, processing each item one by one.
Its basic syntax looks like this:
for item in list; do# commands to run for each itemdone
The item variable will hold each value from the list in turn.
`for` Loop in Action
Let's see the for loop iterate through a list of names. Each name is assigned to the name variable, and then printed.
Try running this example:
#!/bin/bash
echo "--- Greeting Friends ---"
for name in Alice Bob Charlie;
do
echo "Hello, $name!"
done
echo "--- All greeted! ---"`for` Loop for Number Ranges
What if you need to loop a specific number of times, like counting from 1 to 5? You can generate sequences for the for loop:
- Brace Expansion:
{1..5}creates "1 2 3 4 5". seqcommand:$(seq 1 5)also creates "1 2 3 4 5".
Both are handy for numerical iterations.
Counting with `for` Loop
Here's how you can use brace expansion to count up to a specific number. The loop variable i takes on each number in the sequence.
Try running this example:
#!/bin/bash
echo "Counting up!"
for i in {1..3};
do
echo "Count: $i"
done
echo "Done counting."Repeating with `while`
The while loop is used when you want to repeat commands as long as a certain condition remains true. It continuously checks the condition before each iteration.
Its basic structure is:
while condition; do# commands to rundone
The loop stops as soon as the condition becomes false.
`while` Loop Counter
Let's use a while loop to count. We initialize a variable count, and the loop continues as long as count is less than 3.
Remember to update the variable inside the loop, or it might run forever (an 'infinite loop')!
#!/bin/bash
count=0
echo "Starting while loop..."
while [ $count -lt 3 ]; do
echo "Current count: $count"
count=$((count + 1))
done
echo "While loop finished."Repeating `until` True
The until loop is similar to while, but with an inverse condition. It executes commands until a specified condition becomes true.
Its syntax is:
until condition; do# commands to rundone
The loop continues as long as the condition is false.
`until` Loop in Action
Here's an until loop waiting for a variable num to reach 3. It will keep running as long as num is not greater than or equal to 3.
Try running this example:
#!/bin/bash
num=0
echo "Starting until loop..."
until [ $num -ge 3 ]; do
echo "Current number: $num"
num=$((num + 1))
done
echo "Until loop finished."When to Use Which Loop?
Choosing the right loop makes your scripts clearer and more efficient:
forloop: Best for iterating over a known list of items (files, names, numbers in a range).whileloop: Ideal when you need to repeat commands as long as a condition holds true (e.g., reading lines from a file, waiting for user input, counting).untilloop: Useful when you want to repeat commands until a specific condition becomes true (e.g., waiting for a process to finish, retrying an operation).
Loop Challenge
Let's test your understanding of shell loops.
Loops: A Quick Recap
Well done! You've learned the fundamental looping constructs in shell scripting:
- The
forloop iterates over a fixed list of items or a range. - The
whileloop repeats commands as long as a condition is true. - The
untilloop repeats commands until a condition becomes true.
These loops are essential for automating repetitive tasks and making your scripts dynamic and powerful. Keep practicing!
Часто задаваемые вопросы
Урок «Циклы: `for`, `while`, `until`» бесплатный?
Да — полный текст урока «Циклы: `for`, `while`, `until`» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Linux Command Line Mastery, подпишись на CoddyKit PRO. Курс Linux Command Line Mastery содержит 4 уроков всего.
Чему я научусь в уроке «Циклы: `for`, `while`, `until`»?
Автоматизируйте повторяющиеся задачи, освоив различные типы циклов в скриптах оболочки. Ты практикуешь Linux Command Line Mastery с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Linux Command Line Mastery?
Предыдущий опыт не требуется. Linux Command Line Mastery на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Циклы: `for`, `while`, `until`»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Linux Command Line Mastery?
Да. Каждый урок Linux Command Line Mastery включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Переменные, ввод и вывод
- Условные конструкции: `if`, `else`, `case`
- Циклы: `for`, `while`, `until`
- Функции и аргументы в сценариях оболочки