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

15 คำสั่ง Built-in ของ Bash ที่จำเป็น พร้อมตัวอย่างปฏิบัติ

Bash มีคำสั่งจำนวนมากที่มาพร้อมกับ Shell (Built-in) ซึ่งทำงานภายใน Bash Shell เอง

เมื่อคุณรันคำสั่ง Built-in, Bash จะดำเนินการทันทีโดยไม่ต้องเรียกโปรแกรมภายนอก

คำสั่ง Built-in ของ Bash เร็วกว่าคำสั่งภายนอก เพราะคำสั่งภายนอกมักจะต้องสร้าง Process ใหม่ (Fork) เพื่อรัน

ในบทความนี้ เราจะทบทวนคำสั่ง Built-in ที่มีประโยชน์ 15 คำสั่ง พร้อมตัวอย่าง

1. คำสั่ง Export - ส่งออกตัวแปรไปยัง Child Process

คำสั่ง export ใช้สำหรับส่งออกตัวแปรหรือฟังก์ชันไปยัง Environment ของ Child Process ทั้งหมดที่รันอยู่ใน Shell ปัจจุบัน

export varname=value
export -f functionname  # ส่งออกฟังก์ชันใน Shell ปัจจุบัน

คำสั่ง env จะแสดง Environment Variables ทั้งหมด ในตัวอย่างด้านล่าง จะเห็นว่าตัวแปรที่ export ไปแสดงอยู่ใน env

$ export country=India
$ env
SESSIONNAME=Console
country=India
_=/usr/bin/env

คำสั่ง export -p ก็แสดงตัวแปรที่ export ไปทั้งหมดใน Shell ปัจจุบันเช่นกัน

2. คำสั่ง Eval - ประเมินและรัน Expression

คำสั่ง eval จะรวมอาร์กิวเมนต์ทั้งหมดที่ให้มา ประเมิน Expression ที่รวมแล้ว และรันคำสั่งนั้น คืนค่า Exit Status ของคำสั่งที่รัน

$ cat evalex.sh
if [ ! -z $1 ]
then
  proccomm="ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | grep $1"
else
  proccomm="ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu"
fi
eval $proccomm

โค้ดข้างต้นรับอาร์กิวเมนต์เป็น Pattern สำหรับ grep แสดง Process เรียงตาม CPU Usage และกรองตาม Pattern ที่ระบุ

หมายเหตุ: บทความนี้เป็นส่วนหนึ่งของชุดบทช่วยสอน Bash (Bash Tutorial Series)

3. คำสั่ง Hash - จัดการ Hash Table ของคำสั่ง

คำสั่ง hash จัดการ Hash Table ที่เก็บ Path ของคำสั่งที่ใช้ไปแล้ว เมื่อรันคำสั่ง Bash จะค้นหาใน $PATH แต่ถ้ามีใน Hash Table จะดึงมารันทันที Hash Table ยังนับจำนวนครั้งที่ใช้คำสั่งแต่ละคำใน Shell นั้นๆ

$ hash
hits  command
1     /usr/bin/cat
2     /usr/bin/ps
4     /usr/bin/ls

ลบคำสั่งเฉพาะจาก Hash Table ใช้ -d รีเซ็ตทั้งหมดใช้ -r

$ hash -d cat
$ hash
hits  command
2     /usr/bin/ps
4     /usr/bin/ls

4. คำสั่ง PWD - แสดง Current Working Directory

pwd เป็น Built-in สำหรับพิมพ์ Current Working Directory คืนค่าของ Built-in Variable ${PWD}

$ pwd
/home/sasikala/bash/exercises
$ echo $PWD
/home/sasikala/bash/exercises

5. คำสั่ง Readonly - ทำให้ตัวแปร/ฟังก์ชันเป็น Read-only

readonly ใช้ทำเครื่องหมายตัวแปรหรือฟังก์ชันว่า Read-only ไม่สามารถเปลี่ยนแปลงได้อีก

$ cat readonly_ex.sh
#!/bin/bash
# จำกัด Array ให้เป็น readonly
readonly -a shells=("ksh" "bash" "sh" "csh" )
echo ${#shells[@]}
# พยายามแก้ไข Array จะโยน Error
shells[0]="gnu-bash"
echo ${shells[@]}
$ ./readonly_ex.sh
4
readonly_ex.sh: line 9: shells: readonly variable

6. คำสั่ง Shift - เลื่อน Positional Parameters

shift ใช้เลื่อน Positional Parameters ไปทางซ้าย N ครั้ง และ rename ตัวแปรตามลำดับหลังเลื่อน

$ cat shift.sh
#! /bin/bash
while [ $# -gt 0 ]
do
  case "$1" in
    -l) echo "List command"; ls; shift ;;
    -p) echo "Process command"; ps -a; shift ;;
    -t) echo "Hash Table command"; hash; shift ;;
    -h) echo "Help command"; help; shift ;;
  esac
done
$ ./shift.sh -l -t
List command
analysis break testing t1.sh temp
Hash Table command
hits  command
1     /usr/bin/ls

7. คำสั่ง Test - ประเมิน Conditional Expression

test ประเมิน Conditional Expression คืนค่า 0 (True) หรือ 1 (False) ดู Operator เพิ่มเติมได้จาก Manual Page ของ Bash

#! /bin/bash
if test -z $1
then
  echo "The positional parameter \$1 is empty"
fi

8. คำสั่ง Getopts - Parse Command Line Arguments

getopts ใช้ Parse อาร์กิวเมนต์บรรทัดคำสั่ง กำหนดกฎ Option ได้ว่า Option ไหนรับ Argument ไหนไม่รับ ถ้า Option ตามด้วย Colon หมายถึงคาดหวัง Argument สำหรับ Option นั้น

getopts ให้ตัวแปร 2 ตัวคือ $OPTIND (Index ของ Parameter ถัดไป) และ $OPTARG (Argument ของ Option)

$ cat options.sh
#! /bin/bash
while getopts :h:r:l: OPTION
do
  case $OPTION in
    h) echo "help of $OPTARG"; help "$OPTARG" ;;
    r) echo "Going to remove a file $OPTARG"; rm -f "$OPTARG" ;;
  esac
done
$ ./options.sh -h jobs
help of jobs
jobs: jobs [-lnprs] [jobspec ...] or jobs -x command [args]
Lists the active jobs. The -l option lists process id's in addition to the normal information; the -p option lists process id's only.

9. คำสั่ง Logout - ออกจาก Shell ปัจจุบัน

Built-in logout ใช้สำหรับออกจาก Shell ปัจจุบัน

10. คำสั่ง Umask - ตั้งค่า File Mode Creation Mask

umask ตั้งค่า File Mode Creation Mask สำหรับ Process ปัจจุบัน เมื่อ User สร้างไฟล์ Permission เริ่มต้นจะคำนวณจากค่า Umask Permission เริ่มต้นของไฟล์คือ 666 จะถูก Mask กับ Umask Bits

รายละเอียดเพิ่มเติมดูได้ที่บทความ File and Directory Permissions

เมื่อ User สร้างไฟล์ 666 จะถูก Mask ด้วย 022 ดังนั้น Permission เริ่มต้นจะกลายเป็น 644

$ umask 0022
$ > temporary
$ ls -l temporary
-rw-r--r-- 1 root root 4 Jul 26 07:48 temporary

11. คำสั่ง Set - ตั้งค่า/แก้ไข Internal Variables

set เป็น Built-in ใช้ตั้งค่าและแก้ไข Internal Variables ของ Shell set ไม่มี Argument จะแสดง Variables ทั้งหมดและค่า ใช้ตั้งค่า Positional Parameters ได้ด้วย

$ set +o history  # ปิดการเก็บ History (+o ปิด Option)
$ set -o history    # เปิดการเก็บ History (-o เปิด Option)
$ cat set.sh
var="Welcome to thegeekstuff"
set -- $var
echo "\$1=" $1
echo "\$2=" $2
echo "\$3=" $3
$ ./set.sh
$1=Welcome
$2=to
$3=thegeekstuff

12. คำสั่ง Unset - ล้างค่าตัวแปร/ลบ Element ของ Array

unset ใช้ตั้งค่าตัวแปร Shell ให้เป็น Null ใช้ลบ Element ของ Array และลบ Array ทั้งหมดได้

รายละเอียดเพิ่มเติมเกี่ยวกับ Bash Array ดูได้ที่บทความ 15 Bash Array Operations

$ cat unset.sh
#!/bin/bash
# กำหนดค่าและพิมพ์
var="welcome to thegeekstuff"
echo $var
# unset ตัวแปร
unset var
echo $var
$ ./unset.sh
welcome to thegeekstuff

ในตัวอย่างข้างต้น หลัง unset ตัวแปร "var" จะถูกกำหนดเป็น Empty String

13. คำสั่ง Let - คำนวณเลขคณิตบน Shell Variables

let ใช้ทำ Arithmetic Operations บน Shell Variables

$ cat arith.sh
#! /bin/bash
let arg1=12
let arg2=11
let add=$arg1+$arg2
let sub=$arg1-$arg2
let mul=$arg1*$arg2
let div=$arg1/$arg2
echo $add $sub $mul $div
$ ./arith.sh
23 1 132 1

14. คำสั่ง Shopt - ตั้งค่า/ยกเลิก Shell Options

shopt ใช้ตั้งค่าและยกเลิก Shell Options ด้วยคำสั่งนี้ คุณสามารถใช้ความฉลาดของ Shell ได้

$ cat shopt.sh
#! /bin/bash
## ก่อนเปิด xpg_echo
echo "WELCOME\n"
echo "GEEKSTUF\n"
shopt -s xpg_echo
## หลังเปิด xpg_echo
echo "WELCOME\n"
echo "GEEKSTUF\n"
# ก่อนปิด Aliases
alias l.='ls -l .'
l.
# หลังปิด Aliases
shopt -u expand_aliases
l.
$ ./shopt.sh
WELCOME\n
GEEKSTUF\n
WELCOME
GEEKSTUF
total 3300
-rw------- 1 root root 1112 Jan 23 2009 anaconda-ks.cfg
-r-xr-xr-x 1 root root 3252304 Jul 1 08:25 backup
drwxr-xr-x 2 root root 4096 Jan 26 2009 Desktop
shopt.sh: line 17: l.: command not found

ก่อนเปิด Option xpg_echo คำสั่ง Echo ไม่ขยาย Escape Sequences l. เป็น Alias ของ ls -l ของ Current Directory หลังปิด Option expand_aliases Shell ไม่ขยาย Aliases ทำให้เกิด Error l. command not found

15. คำสั่ง Printf - Format Output แบบ C Language

คล้าย printf ในภาษา C, Bash printf Built-in ใช้สำหรับ Format Printing

ในตัวอย่างที่ 13 สคริปต์คำนวณเลขคณิตกับ 2 Inputs ในสคริปต์นั้น แทนที่จะใช้ Echo Statement ให้ใช้ Printf Statement เพื่อพิมพ์ Output ที่จัดรูปแบบแล้ว

ใน arith.sh ให้แทนที่ Echo Statement ด้วย Printf Statement นี้:

printf "Addition=%d\nSubtraction=%d\nMultiplication=%d\nDivision=%f\n" $add $sub $mul $div
$ ./arith.sh
Addition=23
Subtraction=1
Multiplication=132
Division=1.000000