Условные конструкции: `if`, `else`, `case`
Реализуйте логику принятия решений в своих скриптах с помощью различных условных конструкций.
«Условные конструкции: `if`, `else`, `case`» — бесплатный урок Linux Command Line Mastery на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Linux Command Line Mastery, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Linux Command Line Mastery содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Making Decisions in Scripts
In shell scripting, just like in life, you often need to make decisions. Conditional statements allow your scripts to execute different commands based on whether a certain condition is true or false.
This is crucial for creating flexible and powerful scripts that can adapt to different situations or user inputs.
The Basic `if` Statement
The simplest conditional is the if statement. It checks a condition, and if that condition is true, it executes a block of commands. If false, it skips them.
The basic syntax looks like this:
if [ condition ]; then# commands to run if truefi
Remember fi to close the if block!
Simple `if` Example
Let's see a simple if statement in action. This script checks if a variable num is greater than 5.
Try changing the value of num to see how the output changes!
#!/bin/bash
num=7
if [ "$num" -gt 5 ]; then
echo "Number is greater than 5."
fi
num=3
if [ "$num" -gt 5 ]; then
echo "Number is greater than 5. (This won't print)"
fi`if-else`: Two Paths
What if you want to execute one set of commands if a condition is true, and a different set if it's false? That's where else comes in.
The if-else statement provides two distinct paths for your script:
if [ condition ]; then# commands if condition is trueelse# commands if condition is falsefi
Using `if-else`
This script uses if-else to determine if a number is even or odd. We use the arithmetic evaluation (( )) for clearer number comparisons and calculations.
The % operator gives the remainder of a division. If num % 2 is 0, it's even!
#!/bin/bash
num=4
if (( num % 2 == 0 )); then
echo "$num is an even number."
else
echo "$num is an odd number."
fi
num=9
if (( num % 2 == 0 )); then
echo "$num is an even number. (This won't print)"
else
echo "$num is an odd number."
fi`elif`: Multiple Conditions
Sometimes you have more than two possible outcomes. For these situations, you can use elif (short for "else if") to check multiple conditions sequentially.
The script checks conditions one by one. The first one that's true gets its commands executed, and the rest are skipped.
if [ cond1 ]; then ...elif [ cond2 ]; then ...else ...fi
Chain of `elif`
Here's an example using if-elif-else to assign a letter grade based on a score. Notice how the conditions are checked from highest to lowest score.
If a score is 95, the first if condition (>= 90) is met, and it prints "A". The other elif and else blocks are then ignored.
#!/bin/bash
score=85
if [ "$score" -ge 90 ]; then
echo "Grade: A"
elif [ "$score" -ge 80 ]; then
echo "Grade: B"
elif [ "$score" -ge 70 ]; then
echo "Grade: C"
else
echo "Grade: F"
fi`case`: Simple Selection
When you have a single variable or expression that can have many possible values, and you want to perform different actions for each value, the case statement is often cleaner than a long if-elif-else chain.
It's great for menu-driven scripts or handling specific input options.
case $variable inpattern1) commands ;;pattern2) commands ;;*) default commands ;;esac
Using `case` Statements
This script demonstrates how to use case to respond to different user actions (start, stop, restart). The *) pattern acts as a default, catching any unmatched values.
Each block of commands ends with ;;, which is crucial for the case statement to work correctly.
#!/bin/bash
action="start"
case "$action" in
"start")
echo "Starting service..."
;;
"stop")
echo "Stopping service..."
;;
"restart")
echo "Restarting service..."
;;
*) # Default case for anything else
echo "Invalid action: $action"
;;
esac
action="status"
case "$action" in
"start") echo "Starting service..." ;;
"stop") echo "Stopping service..." ;;
"restart") echo "Restarting service..." ;;
*) echo "Invalid action: $action" ;;
esacConditional Challenge
Read the script below carefully. What will be the output when this script is run?
#!/bin/bash
color="blue"
if [ "$color" == "red" ]; then
echo "It's a primary color."
elif [ "$color" == "yellow" ]; then
echo "It's another primary color."
elif [ "$color" == "blue" ]; then
echo "Yes, blue is primary!"
else
echo "Unknown color."
fiDecisions Made Easy
Great job! You've learned the fundamental ways to add decision-making logic to your shell scripts.
if: Executes commands if a condition is true.if-else: Provides two paths, one for true and one for false.elif: Allows chaining multiple conditions for more complex logic.case: A clean way to handle multiple choices based on a single value.
These constructs are essential for writing scripts that can respond dynamically to different inputs and situations.
Часто задаваемые вопросы
Урок «Условные конструкции: `if`, `else`, `case`» бесплатный?
Да — полный текст урока «Условные конструкции: `if`, `else`, `case`» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Linux Command Line Mastery, подпишись на CoddyKit PRO. Курс Linux Command Line Mastery содержит 4 уроков всего.
Чему я научусь в уроке «Условные конструкции: `if`, `else`, `case`»?
Реализуйте логику принятия решений в своих скриптах с помощью различных условных конструкций. Ты практикуешь Linux Command Line Mastery с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Linux Command Line Mastery?
Предыдущий опыт не требуется. Linux Command Line Mastery на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Условные конструкции: `if`, `else`, `case`»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Linux Command Line Mastery?
Да. Каждый урок Linux Command Line Mastery включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Переменные, ввод и вывод
- Условные конструкции: `if`, `else`, `case`
- Циклы: `for`, `while`, `until`
- Функции и аргументы в сценариях оболочки