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

เชี่ยวชาญ Bash Case Statements: 5 ตัวอย่างปฏิบัติสำหรับ Scripting ที่มีประสิทธิภาพ

Bash Shell Case Statement คล้าย Switch Statement ใน C ใช้ Test ค่า Simple เช่น Integers และ Characters ได้

Case Statement ไม่ใช่ Loop ไม่ Execute Block of Code นาน N ครั้ง แทนที่จะเป็น Bash Shell Checks Condition และ Control Flow ของ Program

ในบทความนี้ มาทบทวน Bash Case Command พร้อม 5 ตัวอย่างปฏิบัติ

Case Construct ใน Bash Shell อนุญาตให้ Test Strings กับ Patterns ที่อาจมี Wildcard Characters Bash Case Statement เป็นรูปแบบง่ายที่สุดของ Bash If-Then-Else Statement

Syntax ของ Bash Case Statement:

case expression in
  pattern1 ) statements ;;
  pattern2 ) statements ;;
  ...
esac

Key Points ของ Bash Case Statements:

  • Case Statement ขยาย Expression ก่อนและพยายาม Match กับแต่ละ Pattern
  • เมื่อ Match พบ Statements ที่เกี่ยวข้องทั้งหมดจนถึง Double Semicolon (;;) จะ Execute
  • หลัง Match แรก Case Terminate ด้วย Exit Status ของ Last Command ที่ Execute
  • ถ้าไม่มี Match Exit Status ของ Case คือศูนย์

Bash Case Example 1. ส่ง Signal ให้ Process

Script ต่อไปนี้รับ Signal Number และ Process ID เป็น Arguments และส่ง Signal ให้ Process ID นั้นด้วย Signal Name

Script นี้เพื่อ Demonstrate การใช้ Case Statement

$ cat signal.sh
#!/bin/bash
if [ $# -lt 2 ]
then
  echo "Usage : $0 Signalnumber PID"
  exit
fi
case "$1" in
  1) echo "Sending SIGHUP signal"; kill -SIGHUP $2 ;;
  2) echo "Sending SIGINT signal"; kill -SIGINT $2 ;;
  3) echo "Sending SIGQUIT signal"; kill -SIGQUIT $2 ;;
  9) echo "Sending SIGKILL signal"; kill -SIGKILL $2 ;;
  *) echo "Signal number $1 is not processed" ;;
esac

ในตัวอย่างข้างต้น:

  • $1 และ $2 คือ Signal Number และ Process ID ตามลำดับ
  • ใช้ Kill Command ส่ง Signal ที่ตรงกันให้ Process ID นั้น
  • Execute Sleep Command จำนวนวินาที
  • Optional Last Comparison *) เป็น Default Case Match อะไรก็ได้

Usage ของ Shell Script ข้างต้น: หา Process ID ของ Sleep Command และส่ง Kill Signal ให้ Process ID นั้นเพื่อ Kill Process

$ sleep 1000
$ ps -a | grep sleep
23277 pts/2 00:00:00 sleep
$ ./signal.sh 9 23277
Sending SIGKILL signal
$ sleep 1000
Killed

อ่านเพิ่มเติม Kill Article – 4 Methods to Kill a Process

Bash Case Example 2. Pattern Match ใน File

ตัวอย่างนี้พิมพ์จำนวนบรรทัด จำนวนคำ และลบบรรทัดที่ Match Pattern ที่กำหนด

$ cat fileop.sh
#!/bin/bash
# Check 3 Arguments Given
if [ $# -lt 3 ]
then
  echo "Usage : $0 option pattern filename"
  exit
fi
# Check Given File Exists
if [ ! -f $3 ]
then
  echo "Filename given \"$3\" doesn't exist"
  exit
fi
case "$1" in
  # Count Lines Matches
  -i) echo "Number of lines matches with the pattern $2 :" ; grep -c -i $2 $3 ;;
  # Count Words Matches
  -c) echo "Number of words matches with the pattern $2 :" ; grep -o -i $2 $3 | wc -l ;;
  # Print Matched Lines
  -p) echo "Lines matches with the pattern $2 :" ; grep -i $2 $3 ;;
  # Delete Matched Lines
  -d) echo "After deleting the lines matches with the pattern $2 :" ; sed -n "/$2/!p" $3 ;;
  *) echo "Invalid option" ;;
esac

Execution ของ Script ข้างต้น:

$ cat text
Vim is a text editor released by Bram Moolenaar in 1991 for the Amiga computer.
The name "Vim" is an acronym for "Vi IMproved" because Vim was created as an extended version of the vi editor, with many additional features designed to be helpful in editing program source code.
Although Vim was originally released for the Amiga, Vim has since been developed to be cross-platform, supporting many other platforms.
It is the most popular editor amongst Linux Journal readers.

Bash Case Regex Output หลังลบบรรทัด Match Pattern Vim:

$ ./fileop.sh -d Vim text
It is the most popular editor amongst Linux Journal readers.

อ่านเพิ่มเติม Bash ~ Expansion และ { } Expansion ก่อนหน้า

Bash Case Example 3. หา File Type จาก Extension

ตัวอย่างนี้พิมพ์ Type ของ File (Text, C Source, ฯลฯ) จาก Extension ของ Filename

$ cat filetype.sh
#!/bin/bash
for filename in $(ls)
do
  # Take Extension จาก Filename
  ext=${filename##*\.}
  case "$ext" in
    c) echo "$filename : C source file" ;;
    o) echo "$filename : Object file" ;;
    sh) echo "$filename : Shell script" ;;
    txt) echo "$filename : Text file" ;;
    *) echo " $filename : Not processed" ;;
  esac
done
$ ./filetype.sh
a.c : C source file
b.c : C source file
c1.txt : Text file
fileop.sh : Shell script
obj.o : Object file
text : Not processed
t.o : Object file

Bash Case Example 4. Prompt User ด้วย Yes หรือ No

ใน Software Installation หลายๆ ตัว ระหว่าง License Agreement จะถาม Yes หรือ No Input จาก User Code Snippet ต่อไปนี้เป็นหนึ่งในวิธีได้ Yes/No Input จาก User

$ cat yorno.sh
#!/bin/bash
echo -n "Do you agree with this? [yes or no]: "
read yno
case $yno in
  [yY] | [yY][Ee][Ss] ) echo "Agreed" ;;
  [nN] | [n|N][O|o] ) echo "Not agreed, you can't proceed the installation"; exit 1 ;;
  *) echo "Invalid input" ;;
esac
$ ./yorno.sh
Do you agree with this? [yes or no]: YES
Agreed

ถ้ามี Patterns หลายตัวคั่นด้วย Pipe Characters Expression สามารถ Match ได้กับอันไหนก็ได้ในลำดับเพื่อ Execute Associated Statements Patterns ถูก Check ตามลำดับจนกว่าจะเจอ Match ถ้าไม่เจออะไรเลย ไม่มีอะไรเกิดขึ้น

อ่านเพิ่มเติม 15 Bash Array Examples Article ก่อนหน้า

Bash Case Example 5. Startup Script

Startup Scripts ใน /etc/init.d Directory ใช้ Case Statement เพื่อ Start และ Stop Application

ใช้ Patterns อะไรก็ได้ แต่นิยม Case Statement ตอน Test ค่า Primitives (เช่น Integers หรือ Characters)

$ cat startpcapp
#!/bin/bash
case "$1" in
  'start') echo "Starting application" ; /usr/bin/startpc ;;
  'stop') echo "Stopping application" ; /usr/bin/stoppc ;;
  'restart') echo "Usage: $0 [start|stop]" ;;
esac
$ ./startpcapp start
Starting application
/usr/bin/startpc started

Recommended Reading

Bash 101 Hacks, by Ramesh Natarajan ผมใช้เวลาส่วนใหญ่กับ Linux Environment จึงเป็นแฟนใหญ่ของ Bash Command Line และ Shell Scripting 15 ปีก่อน ทำงานบน *nix หลายรสชาติ เคยเขียน Code มากบน C Shell และ Korn Shell ต่อมาเริ่มทำงานบน Linux เป็น System Administrator Automate ทุกอย่างที่เป็นไปได้ด้วย Bash Shell Scripting จากประสบการณ์ Bash เขียน Bash 101 Hacks eBook ที่มี 101 ตัวอย่างปฏิบัติทั้ง Command Line และ Shell Scripting หากคิดจะ Master Bash ให้ทำความดีใจตัวเองและอ่านหนังสือเล่มนี้ จะช่วยให้ควบคุม Bash Command Line และ Shell Scripting ได้อย่างเต็มที่