Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

Bash If-Else Syntax: เรียนรู้การตัดสินใจใน Linux Shell

Syntax ของ if Statements

if...else เป็น conditional statement ที่ใช้บ่อยที่สุด Bash รองรับเช่นกัน 3 รูปแบบ:

  • Single if: if...then...fi
  • if...else: if...then...else...fi
  • if..elif..else: if..elif..else..fi

การใช้ if Statement

if [ condition ]; then
    statement
fi

สำคัญ: spaces เป็นส่วนหนึ่งของ syntax ห้ามลบ

ตัวอย่าง: เปรียบเทียบ 2 ตัวเลข

#!/bin/sh
a=5
b=30
if [ $a -lt $b ]; then
    echo "a is less than b"
fi

Output: a is less than b

การใช้ if .. else Statement

if [ condition ]; then
    statement
else
    do this by default
fi

ตัวอย่าง: a=99, b=45 -> condition false -> run else block

Output: a is greater than b

การใช้ if..elif..else Statements

if [ condition ]; then
    statement
elif [ condition ]; then
    statement
else
    do this by default
fi

ใช้ logical operators AND -a OR -o

ตัวอย่าง: กำหนดประเภทสามเหลี่ยม

read a
read b
read c
if [ $a == $b -a $b == $c -a $a == $c ]; then
    echo EQUILATERAL
elif [ $a == $b -o $b == $c -o $a == $c ]; then
    echo ISOSCELES
else
    echo SCALENE
fi

Input: 3 4 5 -> Output: SCALENE

สรุป

คุณสามารถแบ่ง branching ของโค้ดตามเงื่อนไข if..else ได้ง่าย ทำให้โค้ด dynamic มากขึ้น บทช่วยสอนนี้ครอบคลุม syntax และตัวอย่าง