0Pricing
Linux Command Line Mastery · 강의

조건문: `if`, `else`, `case`

다양한 조건 구성 요소를 사용하여 스크립트에 의사 결정 로직을 구현합니다.

조건문: `if`, `else`, `case`은(는) CoddyKit의 무료 Linux Command Line Mastery 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 true
  • fi

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 true
  • else
  • # commands if condition is false
  • fi

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 in
  • pattern1) 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" ;;

esac

Conditional 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."
fi

Decisions 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 AI 튜터), CoddyKit PRO로 업그레이드하면 Linux Command Line Mastery 강의 전체를 잠금 해제할 수 있습니다. Linux Command Line Mastery 강의에는 총 4개의 강의가 포함되어 있습니다.

“조건문: `if`, `else`, `case`”에서 뭘 배우나요?

다양한 조건 구성 요소를 사용하여 스크립트에 의사 결정 로직을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Linux Command Line Mastery을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Linux Command Line Mastery을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Linux Command Line Mastery은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“조건문: `if`, `else`, `case`” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Linux Command Line Mastery 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Linux Command Line Mastery 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 변수, 입력 및 출력
  2. 조건문: `if`, `else`, `case`
  3. 반복문: `for`, `while`, `until`
  4. 셸 스크립트의 함수와 인수
← Linux Command Line Mastery(으)로 돌아가기