7.การวนรอบ โดยใช้คำสั่ง for, while และ until

คำสั่ง for มีลักษณะคล้าย for ในภาษาไพธอน มีรูปแบบเป็น

for VAR in SCOPE; do
    COMMAND
done

คำสั่ง while มีรูปแบบเป็น

while [ CONDITION ]; do
    COMMAND
done

ตราบใดที่เงื่อนไข CONDITION ยังเป็นจริง ก็จะทำคำสั่ง COMMAND ซ้ำไปเรื่อย ๆ

คำสั่ง until มีความหมายตรงกันข้ามกับ while โดยมีรูปแบบเป็น

until [ CONDITION ]; do
    COMMAND
done

คือจะทำคำสั่ง COMMAND จนกว่าเงื่อนไข CONDITION จะเป็นจริง

7.1 ตัวอย่าง for

#!/bin/bash
for i in $( ls ); do
    echo item: $i
done

เป็นการนำผลลัพธ์ของคำสั่ง ls ไปเป็นตัวแปรชั่วคราวในการกำหนดขอบเขตให้กับตัวแปร i ในคำสั่ง for

ในที่นี้จะทำการแสดงผลว่า item: FILENAME ...

7.2 ตัวอย่าง for อีกแบบ

#!/bin/bash
for i in `seq 1 10`; do
    echo $i
done

เป็นการนำผลจากคำสั่ง seq 1 10 ไปกำหนดขอบเขตให้กับตัวแปร i ในคำสั่ง for

อาจเขียนเลียนแบบตัวอย่าง 7.1 ได้เหมือนกันดังนี้

#!/bin/bash
for i in $( seq 1 10 ); do
    echo $i
done

7.3 ตัวอย่าง while

#!/bin/bash 
COUNTER=0
while [ $COUNTER -lt 10 ]; do
    echo The counter is $COUNTER
    let COUNTER=COUNTER+1 
done

เป็นการแสดงค่าตัวแปร COUNTER ที่เพิ่มขึ้นทีละ 1 จาก 0 ถึง 9

โปรดสังเกตการใช้ตัวแปรเก็บค่าตัวเลข, การเปรียบเทียบตัวเลขโดยใช้ตัวเปรียบเทียบ -lt (less than) และการกำหนดเพิ่มค่าให้กับตัวแปรแบบตัวเลขโดยใช้คำสั่ง let

7.3 ตัวอย่าง until

#!/bin/bash 
COUNTER=20
until [ $COUNTER -lt 10 ]; do
    echo COUNTER $COUNTER
    let COUNTER-=1
done

จะแสดงตัวเลขตั้งแต่ 20 ลดลงทีละ 1 จนถึง 10

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.