6. ประโยคเงื่อนไข

6.1 รูปแบบ

มีรูปแบบคือ

if [ EXPRESSION ]; then
    CODE IF 'EXPRESSION' IS TRUE.
[elif [ EXPRESSION-ELIF ]; then
    CODE IF 'EXPRESSION-ELIF' IS TRUE.]
[else
    CODE IF NOTHING IS TRUE.]
fi

6.2 ตัวอย่าง if ... then

#!/bin/bash
if [ "foo" = "foo" ]; then
    echo expression evaluated as true
fi

โค้ดนี้จะเป็นจริงเสมอ ดังนั้นข้อความ "expression evaluated as true" จะถูกพิมพ์ออกมาเสมอ

6.3 ตัวอย่าง if ... then ... else

#!/bin/bash
if [ "foo" = "foo" ]; then
   echo expression evaluated as true
else
   echo expression evaluated as false
fi

โค้ดนี้จะเป็นจริงเสมอ ดังนั้นข้อความ "expression evaluated as true" จะถูกพิมพ์ออกมาเสมอ

6.4 ตัวอย่างแบบใช้ตัวแปร

#!/bin/bash
T1="foo"
T2="bar"
if [ "$T1" = "$T2" ]; then
    echo expression evaluated as true
else
    echo expression evaluated as false
fi

ตัวอย่างนี้จะเป็นเท็จเสมอ

สังเกตการใช้ตัวแปรในการเปรียบเทียบ ควรให้ตัวแปรอยู่ในเครื่องหมายคำพูดเสมอ เพื่อป้องการการผิดพลาดจากการแทนค่าที่ซับซ้อน หรือการที่มีช่องว่างในค่าตัวแปร

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <blockquote> <img> <h3> <h4> <h5>
  • Lines and paragraphs break automatically.
  • E-Mail addresses are hidden with reCAPTCHA Mailhide.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.