Bash Shell Functions เป็นวิธีจัดกลุ่ม UNIX/Linux Commands หลายคำสั่งเพื่อ Execute ภายหลังด้วยชื่อเดียว Bash Shell Function รันได้เหมือน Unix Command ปกติ Shell Functions Execute ใน Current Shell Context โดยไม่สร้าง Process ใหม่
ทั้ง Bash Aliases และ Functions ช่วย Define Shortcuts สำหรับ Commands ที่ยาวหรือซับซ้อน แต่ Aliases ไม่อนุญาต Control-flows, Arguments และ Tricks ต่างๆ ที่ Functions ทำได้
บทความนี้เป็นส่วนหนึ่งของชุดบทช่วยสอน Bash ต่อเนื่อง ดูบทช่วยสอนก่อนหน้าเกี่ยวกับ Bash Introduction, Bash Exit Status และ Bash Alias Examples
Syntax สำหรับสร้าง Bash Function:
function functionname() {
commands
.
.
}
- function เป็น Keyword ซึ่ง Optional
- functionname คือชื่อ Function
- commands – รายการ Commands ที่จะ Execute ใน Function
Function รับ Arguments ได้ ระหว่าง Execution Arguments ของ Function จะกลายเป็น Positional Parameters Positional Parameter 0 จะมี Scriptname ซึ่งไม่เปลี่ยนแปลง
เรียก Bash Function จาก Command Line:
$ functionname arg1 arg2
- เมื่อ Shell Interpret Linux Command มันจะมอง Special Built-in Functions ก่อน (break, continue, eval, exec ฯลฯ) แล้วค่อยมอง Shell Functions
- Exit Status ของ Bash Function คือ Exit Status ของคำสั่งสุดท้ายที่ Execute ใน Function Body
หมายเหตุ: วาง Shell Function Definitions ใน Shell Startup File (เช่น .bash_profile) วิธีนี้ Function จะพร้อมใช้จาก Command Line ตลอดเวลา ดู Bash Execution Sequence Article ก่อนหน้าเพื่อรู้ว่า .bash_profile Execute เมื่อไหร่
ตัวอย่าง 1: Function แสดง Long List ของ Files ด้วย Extension ที่กำหนด
Function lsext ใช้หา List of Files ใน Current Directory ที่มี Extension ที่กำหนด ใช้ Combination ของ Find Command และ ls Command
$ function lsext() {
find . -type f -iname '*.'${1}'' -exec ls -l {} \; ;
}
$ cd ~
$ lsext txt
-rw-r--r-- 1 root root 24 Dec 15 14:00 InMorning.txt
-rw-r--r-- 1 root root 184 Dec 16 11:45 Changes16.txt
-rw-r--r-- 1 root root 458 Dec 18 11:04 Changes18.txt
-rw-r--r-- 1 root root 1821 Feb 4 15:01 ChangesOfDB.txt
ตัวอย่าง 2: Bash Function รัน Linux Command บนกลุ่มไฟล์
ในตัวอย่างต่อไปนี้ Function batchexec หา Files ด้วย Extension ที่กำหนด และ Execute Command ที่กำหนดบน Files ที่ Select
$ function batchexec() {
find . -type f -iname '*.'${1}'' -exec ${@:2} {} \; ;
}
$ cd ~
$ batchexec sh ls
$ batchexec sh chmod 755
$ ls -l *.sh
-rwxr-xr-x 1 root root 144 Mar 9 14:39 debug.sh
-rwxr-xr-x 1 root root 5431 Jan 25 11:32 get_opc_vers.sh
-rwxr-xr-x 1 root root 22 Mar 18 08:32 t.sh
ในตัวอย่างข้างต้น หา Shell Script Files ทั้งหมดที่มี .sh Extension และเปลี่ยน Permission เป็น 755 (All Permission สำหรับ User, Group และ Others Read และ Execute) ใน Function Definition สังเกต ${@:2} ซึ่งให้ Parameter ที่ 2 ขึ้นไป (Shell Expansion Feature)
ตัวอย่าง 3: Bash Function สร้าง Random Password
Function ต่อไปนี้ใช้สร้าง Random Strong Passwords พร้อม Special Characters สำหรับความยาวที่กำหนด ถ้าไม่ระบุความยาว Default 12 Characters
$ function rpass() {
cat /dev/urandom | tr -cd '[:graph:]' | head -c ${1:-12}
}
$ rpass 6
-Ju.T[[
$ rpass
Gz1f!aKN^""k
ในตัวอย่างข้างต้น เมื่อ rpass รันด้วย Argument 6 จะสร้าง Password 6 Characters และ rpass โดยไม่มี Argument สร้าง 12 Characters ${1:-12} หมายถึงถ้า $1 Unset หรือ Null ให้คืน 12 มิฉะนั้นคืนค่า $1
ตัวอย่าง 4: Bash Function หา IP Address ของ Interface ที่กำหนด
ตัวอย่างต่อไปนี้ Define Function ชื่อ getip รับ Interface Name เป็น Argument และให้ IP Address ที่ Assign บน Interface นั้น (Default คืนค่า eth0 IP Address) ใช้ ifconfig Command
$ function getip() {
/sbin/ifconfig ${1:-eth0} | awk '/inet addr/ {print $2}' | awk -F: '{print $2}';
}
$ getip
15.110.106.86
$ getip eth0
15.110.106.86
$ getip lo
127.0.0.1
ตัวอย่าง 5: Bash Function พิมพ์รายละเอียดเครื่อง
ตัวอย่างนี้ Define Function ให้ข้อมูลที่จำเป็นทั้งหมดเกี่ยวกับ Machine Users สามารถ Define และ Call Function นี้ใน Startup Files เพื่อได้ข้อมูลตอน Startup
$ function mach() {
echo -e "\nMachine information:" ; uname -a
echo -e "\nUsers logged on:" ; w -h
echo -e "\nCurrent date :" ; date
echo -e "\nMachine status :" ; uptime
echo -e "\nMemory status :" ; free
echo -e "\nFilesystem status :"; df -h
}
$ mach
Machine information:
Linux dev-db 2.6.18-128.el5 #1 SMP Wed Dec 17 11:41:38 EST 2008 x86_64 GNU/Linux
Users logged on:
root pts/2 ptal.mot Wed10 0.00s 1.35s 0.01s w -h
Current date :
Thu Mar 18 11:59:36 CET 2010
Machine status :
11:59:36 up 7 days, 3 min, 1 user, load average: 0.01, 0.15, 0.15
Memory status :
total used free shared buffers cached
Mem: 2059768 2033212 26556 0 81912 797560
-/+ buffers/cache: 1153740 906028
Swap: 4192956 48164 4144792
Filesystem status :
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 12G 12G 0 100% /
tmpfs 1006M 377M 629M 38% /dev/shm
/dev/sdc5 9.9G 409M 9.0G 5% /mydisk
ตัวอย่าง 6: Bash Function จัดรูปแบบ ls Output ให้ดียิ่งขึ้น
Function ต่อไปนี้จะ Clear Screen, วาง Cursor Top ของ Screen, Execute ls, แล้ววาง Cursor End ของ Screen
$ function ll () {
clear; tput cup 0 0; ls --color=auto -F --color=always -lhFrt; tput cup 40 0;
}
$ ll
แสดง Code ของ Function ด้วย Type Command
type เป็น Shell Built-in ใช้ดู Function Code
Syntax: type function-name
$ type ll
ll is a function
ll () {
clear; tput cup 0 0; ls --color=auto -F --color=always -lhFrt; tput cup 40 0;
alias ls="ls --color=auto -F"
}
สำหรับ Reference ง่ายๆ ดู Function ทั้ง 6 ตัวจาก Sample .bash_profile Functions File นี้
เพิ่ม Functions ทั้งหมดนี้ใน ~/.bash_profile File เพื่อให้เข้าถึง Functions ได้ตลอดเวลาโดยไม่ต้องสร้างใหม่ทุกครั้ง