8.ฟังก์ชั่น (functions)

ในการใช้งานเชลล์สคริปต์แบบจริงจัง เราจำเป็นต้องเขียนฟังก์ชันเพื่อประโยชน์ในการเรียกใช้งานแบบซ้ำ ๆ เพื่อให้ประหยัดการเขียนโค้ด และให้โค้ดดูง่าย

มีรูปแบบเป็น

function FUNCTION_NAME {
    COMMAND
}

หรือ

FUNCTION_NAME () {
    COMMAND
}

โปรแกรมจะเว้นไม่ถูกเรียกทำงานในช่วงตั้งแต่ชื่อฟังก์ชันจนกระทั่งจบบล็อก { COMMAND }

เรานิยมวางฟังก์ชันไว้ที่ต้นโปรแกรม เพื่อให้สามารถถูกเรียกจากโค้ดหลักได้

8.1 ตัวอย่างฟังก์ชัน

#!/bin/bash

function quit {
    exit
}

function hello {
    echo Hello!
}

hello
quit
echo foo

ตัวอย่างนี้ บรรทัดที่ 13 คือคำสั่ง echo foo จะไม่ถูกเรียกใช้ เนื่องจากโปรแกรมจะหลุดสู่เชลล์ในบรรทัดที่ 12 คือคำสั่ง quit

8.2 ตัวอย่างฟังก์ชันที่มีการส่งผ่านค่าตัวแปร

#!/bin/bash

function quit {
    exit
}

function ex {
    echo $1 
}

ex Hello
ex World
quit
echo foo

จากตัวอย่าง จะเห็นการส่งผ่านข้อความเข้าไปในฟังก์ชัน ex ด้วยตัวแปร $1

ในทำนองเดียวกัน ถ้ามีการส่งผ่านตัวแปรหลายตัว ก็จะใช้รูปแบบเป็น $2, $3, ... โดยเรียกใช้งานด้วยรูปแบบ ex VAR1 VAR2 VAR3 ... ตามลำดับ

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.