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

เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

การสร้าง Shell Scripts เป็นทักษะสำคัญที่สุดที่ Linux Users ควรมีที่ปลายนิ้ว Shell Scripts มีบทบาทมากในการ Automate Repetitive Tasks ที่ไม่เช่นนั้นจะ Tedious 執行ทีละบรรทัด

ใน Tutorial นี้ Highlight Basic Shell Scripting Operations ที่ Linux User ทุกคนควรมี

1. สร้าง Simple Shell Script

Shell Script เป็นไฟล์ประกอบ ASCII Text เริ่มสร้าง Simple Shell Script ด้วย Text Editor มี Editor หลายตัว Command-line และ GUI-based สำหรับ Guide นี้ใช้ Vim Editor

เริ่มสร้าง Script แสดง Hello World เมื่อ Execute

$ vim hello.sh

วางเนื้อหาด้านล่างในไฟล์และ Save

#!/bin/bash
# Print Hello world message
echo "Hello World!"

มา Review Script บรรทัดต่อบรรทัด:

  • บรรทัดแรก #!/bin/bash เรียกว่า Shebang Header Special Construct ระบุ Program ที่จะ Interpret Script ในกรณีนี้คือ Bash Shell ระบุด้วย /bin/bash ภาษา Scripting อื่นๆ เช่น Python (#!/usr/bin/python3) และ Perl (#!/usr/bin/perl)
  • บรรทัดที่สองเป็น Comment Statement อธิบาย Script ทำอะไร ไม่ Execute เมื่อรัน Script Comments นำหน้าด้วย Hash Sign #
  • บรรทัดสุดท้ายเป็น Command พิมพ์ข้อความ Hello World บน Terminal

ขั้นต่อไป ทำให้ Script Executable ด้วย chmod Command:

$ chmod +x hello.sh

สุดท้าย รัน Shell Script ด้วยคำสั่งใดคำสั่งหนึ่ง:

$ bash hello.sh OR $ ./hello.sh
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

2. ใช้ Conditional Statements Execute Code

เหมือนภาษาอื่นๆ Conditional Statements ใช้ใน Bash Scripting ทำ Decisions ด้วย Syntax แตกต่างนิดหน่อย จะครอบคลุม if, if-else, และ elif

ตัวอย่าง If Statement เท่านั้น

If Statement ใช้ Test Single หรือ Multiple Conditions เริ่มจาก Fundamental Use ของ If Test Single Condition If Statement Defined โดย Blocks if ... fi

if command
then
  statement
fi

ดู Shell Script ด้านล่าง:

#!/bin/bash
echo 'Enter the score'
read x
if [[ $x == 70 ]]; then
  echo 'Good job!'
fi

Script ข้างบน Prompt User ให้ Score เก็บใน Variable x หาก Score เท่ากับ 70 จะ Output Good job! Comparison Operator == Test ว่า Score ใน Variable x เทียบเท่า 100 (หมายเหตุ: โค้ดต้นฉบับมี Typo เปรียบเทียบ 70 แต่ Comment บอก 100)

เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

Comparison Operators อื่นๆ ที่ใช้ได้:

  • -eq - Equal to
  • -ne - Not equal to
  • -lt - Less than
  • -le - Less than or equal to
  • -lt - Less than (ซ้ำ)
  • -ge - Greater than or equal to

ตัวอย่าง If-statement Block ด้านล่างพิมพ์ Work Harder หาก Input Score น้อยกว่า 50

if [[ $x -lt 50 ]]; then
  echo 'Work Harder!'
fi
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

ตัวอย่าง If-else Statement

สถานการณ์ 2 ผลลัพธ์: This หรือ That If-else Statement ช่วยได้

if command
then
  statement1
else
  statement2
fi

Script ด้านล่างอ่าน Input Score เช็คว่ามากกว่าหรือเท่า 70

ถ้า Score มากกว่าหรือเท่า 70 ได้ข้อความ Great job, You passed! แต่ถ้าต่ำกว่า 70 จะพิมพ์ You failed

#!/bin/bash
echo 'Enter the score'
read x
if [[ $x -ge 70 ]]; then
  echo 'Great job, You passed!'
else
  echo 'You failed'
fi
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

ตัวอย่าง If-elif-else Statement

สถานการณ์ Multiple Conditions และ Different Outcomes ใช้ If-elif-else Format:

if condition1
then
  statement1
elif condition2
then
  statement2
else
  statement3
fi

ตัวอย่าง Script Lottery เช็คหมายเลขที่ป้อนเป็น 90, 60 หรือ 30

#!/bin/bash
echo 'Enter the score'
read x
if [[ $x -eq 90 ]]; then
  echo "You have won the First Prize"
elif [[ $x -eq 60 ]]; then
  echo "You have won the Second Prize"
elif [[ $x -eq 30 ]]; then
  echo "You have won the Second Prize"
else
  echo "Please try again"
fi
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

3. ใช้ If Statement ด้วย AND Logic

ใช้ If Statement พร้อม AND Logic Operator Execute Task หาก 2 Conditions เป็นจริง Operator && ใช้แทน AND Logic

#!/bin/bash
echo 'Please Enter your user_id'
read user_id
echo 'Please Enter your tag_no'
read tag_id
if [[ ($user_id == "tecmint" && $tag_id -eq 3990) ]]; then
  echo "Login successful"
else
  echo "Login failure"
fi

5. ใช้ If Statement ด้วย OR Logic

ใช้ OR Logic แทนด้วย Symbol || ต้องการแค่ Condition หนึ่งเป็นจริง Script จะให้ผลลัพธ์

#!/bin/bash
echo 'Please enter a random number'
read number
if [[ (number -eq 55 || number -eq 80) ]]; then
  echo 'Congratulations! You've won'
else
  echo 'Sorry, try again'
fi
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

ใช้ Looping Constructs

Bash Loops ให้ Users ทำ Series of Tasks จนได้ Result ที่ต้องการ ช่วย Repetitive Tasks ใน Section นี้ จะ Peek Loops บางตัวที่หาได้ในภาษาอื่นๆ

While Loop

Loop ง่ายที่สุด Syntax เรียบง่าย:

while 
do
  commands
done

While Loop ด้านล่าง List Numbers 1 ถึง 10 เมื่อ Execute

#!/bin/bash
# A simple while loop
counter=1
while [ $counter -le 10 ]
do
  echo $counter
  ((counter++))
done

มา Discuss While Loop:

Variable Counter Initialize เป็น 1 และ While Variable น้อยกว่าหรือเท่า 10 Value ของ Counter จะ Increment จน Condition Satisfied บรรทัด echo $counter พิมพ์เลข 1 ถึง 10

เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

For Loop

เหมือน While Loop For Loop ใช้ Execute Code Iteratively กล่าวคือ Repeat Code Execution กี่ครั้งก็ได้ที่ User Define

Syntax:

for var in 1 2 3 4 5 N
do
  command1
  command2
done

For Loop ด้านล่าง Iterate 1 ถึง 10 ประมวลผล Values บนหน้าจอ

เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

วิธีดีกว่า Define Range ด้วย Double Curly Braces { } แทนการพิมพ์เลขทั้งหมด

#!/bin/bash
# Specify range in a for loop
for num in {1..10}
do
  echo $num
done

Bash Positional Parameters

Positional Parameter เป็น Special Variable เรียกใน Script เมื่อ Values ถูกส่งผ่าน Shell แต่ไม่สามารถ Assign ได้ Positional Parameters รันจาก $0 $1 $2 $3 ... ถึง $9 เกิน $9 ต้อง Enclose ใน Curly Braces เช่น ${10}, ${11} ฯลฯ

ตอน Execute Script Parameter แรก $0 รับชื่อ Shell Script $1 รับ Variable แรกที่ส่งบน Terminal $2 รับตัวที่สอง $3 ตัวที่สาม ฯลฯ

สร้าง Script test.sh ดังนี้:

#!/bin/bash
echo "The name of the script is: " $0
echo "My first name is: " $1
echo "My second name is: " $2

Execute Script ให้ First และ Second Name เป็น Arguments:

# bash test.sh James Kiarie
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

จาก Output เห็น Variable แรกพิมพ์คือชื่อ Shell Script กรณีนี้ test.sh ตามด้วย Names ตาม Positional Parameters ที่ Define ใน Script

Positional Parameters 有用 เพราะช่วย Customize Data ที่ป้อนแทนการ Assign ค่าให้ Variable อย่างชัดเจน

Shell Command Exit Codes

ตอบคำถามง่าย: Exit Code คืออะไร?

ทุก Command Executed บน Shell โดย User หรือ Shell Script มี Exit Status เป็น Integer

Exit Status 0 หมายถึง Command Executed Successfully ไม่มี Errors อะไรกว่า 1 ถึง 255 แสดงว่า Command Failed หรือไม่ Execute Successfully

หา Exit Status ของ Command ด้วย $? Shell Variable

Exit Status 1 ชี้ไป General Error หรือ Impermissible Errors เช่น Edit Files โดยไม่มี Sudo Permissions

Exit Status 2 ชี้ไป Incorrect Usage ของ Command หรือ Builtin Shell Variable

Exit Status 127 ชี้ไป Illegal Command ปกติให้ Error command not found

เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

Processing Output ของ Shell Commands ภายใน Script

ใน Bash Scripting เก็บ Output ของ Command ใน Variable ไว้ใช้ภายหลัง เรียกว่า Shell Command Substitution ทำได้ดังนี้:

variable=$(command) OR variable=$(/path/to/command) OR variable=$(command argument1 argument2 ...)

ตัวอย่าง เก็บ Command date ใน Variable today เรียก Shell Script เปิดเผย Current Date

#!/bin/bash
today=$(date)
echo "Today is $today"
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

อีกตัวอย่าง หา Valid Login Users บน Linux System ทำยังไง? ก่อนอื่น List ของ Users ทั้งหมด (System, Process, Login Users) เก็บใน /etc/passwd

ดูไฟล์ด้วย Cat Command แต่ 좁혀ไป Login Users ใช้ Grep ค้นหา Users ที่มี Attribute /bin/bash และ cut -c 1-10 แสดง 10 ตัวอักษรแรกของชื่อ

เก็บ Cat Command ไว้ใน Variable login_users

#!/bin/bash
login_users=$(cat /etc/passwd | grep /bin/bash | cut -c 1-10)
echo 'This is the list of login users:'
echo $login_users
เชี่ยวชาญ Simple Shell Scripts ใน Linux: คู่มือขั้นตอน

จบ Tutorial สร้าง Simple Shell Scripts หวังว่าจะมีประโยชน์