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

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Shell scripting เป็นส่วนสำคัญของ process automation ใน Linux Scripting ช่วยเขียน sequence ของคำสั่งในไฟล์ แล้ว execute พวกมัน

ประหยัดเวลาเพราะไม่ต้องพิมพ์คำสั่งซ้ำๆ สามารถทำ daily tasks ได้อย่างมีประสิทธิภาพ และ schedule ให้รันอัตโนมัติ

ยังสามารถตั้ง script ให้รันตอน startup เช่น แสดงข้อความตอนเปิด session ใหม่ หรือตั้ง environment variables

Applications และ uses ของ scripting มากมาย มาเจาะลึกกันเลย

ในบทความนี้คุณจะเรียนรู้:

  1. Bash shell คืออะไร?
  2. Bash script คืออะไร และ identify ยังไง?
  3. สร้าง first bash script และ execute ยังไง?
  4. Basic syntax ของ shell scripting
  5. ดู system's scheduled scripts ยังไง?
  6. Automate scripts โดย scheduling ผ่าน cron jobs ยังไง?

วิธีเรียนดีที่สุดคือ practice ผมแนะนำ follow along ด้วย Replit เข้าถึง running Linux shell ได้ภายในนาที

Introduction to the Bash Shell

Linux command line มาจาก program เรียกว่า shell ตลอดกาล shell program evolved เพื่อ cater various options

Different users configured ใช้ different shells แต่ most users ชอบ default shell Default shell สำหรับหลาย Linux distros คือ GNU Bourne-Again Shell (bash) Bash succeeded by Bourne shell (sh)

ตอน launch shell ครั้งแรก มันใช้ startup script ใน .bashrc หรือ .bash_profile ให้ customize shell behavior

ตอน shell ใช้ interactively มันแสดง $ รอคำสั่งจาก user เรียกว่า shell prompt

[username@host ~]$

ถ้า shell รัน as root prompt เปลี่ยนเป็น # Superuser shell prompt:

[root@host ~]#

Bash powerful มาก เพราะ simplify operations ที่ยาก accomplish efficiently ด้วย GUI จำไว้ว่า most servers ไม่มี GUI เรียนรู้ CLI powers จึงสำคัญ

Bash Script คืออะไร?

Bash script คือ series ของ commands เขียนในไฟล์ อ่านและ execute โดย bash program Program execute ทีละบรรทัด

เช่น navigate ไป path เฉพาะ สร้าง folder และ spawn process ภายใน ด้วย command line

ทำ sequence เดียวกันได้โดย save commands ใน bash script และ run มัน รัน script กี่ครั้งก็ได้

Identify Bash Script ยังไง?

File extension .sh.

By naming conventions bash scripts ลงท้ายด้วย .sh แต่ bash scripts รันได้ดีแม้ไม่มี sh extension

Scripts เริ่มด้วย shebang.

Scripts identified ด้วย shebang Shebang = bash # + bang ! ตามด้วย bash shell path บรรทัดแรกของ script Shebang บอก shell ให้ execute via bash shell Shebang คือ absolute path ไป bash interpreter

ตัวอย่าง shebang statement:

#! /bin/bash

Path ของ bash program อาจต่างกัน จะดูภายหลังวิธี identify

Execution rights

Scripts มี execution rights สำหรับ user ที่ execute

Execution right แทนด้วย x ตัวอย่าง user มี rwx (read, write, execute) rights สำหรับ test_script.sh

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

File colour

Executable scripts แสดงสีต่างจาก files/folders อื่นๆ

ในกรณีผม scripts ที่มี execution rights แสดงเป็นสีเขียว

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

สร้าง Bash Script แรก

สร้าง simple script output Hello World

สร้างไฟล์ hello_world.sh

touch hello_world.sh

หา path ของ bash shell

which bash
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

ในกรณีผม path คือ /usr/bin/bash ใส่ใน shebang

เขียนคำสั่ง

จะ echo "hello world" ไป console

Script จะเป็นแบบนี้:

#! usr/bin/bash echo "Hello World"

Edit ไฟล์ hello_world.sh ด้วย text editor ใดก็ได้ ใส่บรรทัดข้างบน

ให้ execution rights กับ user

Modify file permissions อนุญาต execute script:

chmod u+x hello_world.sh

chmod modify existing rights ของไฟล์สำหรับ user เพิ่ม +x ให้ user u

Run script

รัน script ได้ 2 วิธี:

./hello_world.sh

bash hello_world.sh

Output:

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Basic Syntax ของ Bash Scripting

เหมือน programming languages อื่นๆ bash scripting follow rules สร้าง programs เข้าใจได้โดยคอมพิวเตอร์ ส่วนนี้เรียนรู้ syntax

Define variables ยังไง?

Define variable syntax variable_name=value ดึงค่า variable ใส่ $ นำหน้า

#!/bin/bash # A simple variable example greeting=Hello name=Tux echo $greeting $name 
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Tux คือชื่อ Linux mascot penguin

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Arithmetic Expressions

Operators ที่ bash รองรับสำหรับคำนวณคณิตศาสตร์:

Operator Usage
+ addition
- subtraction
* multiplication
/ division
** exponentiation
% modulus

ลองตัวอย่าง:

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Numerical expressions คำนวณและเก็บใน variable syntax:

var=$((expression))

ลองตัวอย่าง:

#!/bin/bash var=$((3+9)) echo $var 
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Fractions คำนวณไม่ถูกต้องด้วยวิธีข้างบน truncated

สำหรับ decimal calculations ใช้ bc command ได้ output จำนวน decimal places ที่ต้องการ bc (Bash Calculator) command line calculator รองรับคำนวณ decimal points

echo "scale=2;22/7" | bc

scale define decimal places ที่ต้องการใน output

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

อ่าน user input ยังไง?

บางครั้งต้อง gather user input และ perform operations

ใน bash อ่าน user input ด้วยคำสั่ง read

read variable_name

Prompt user ด้วย custom message ใช้ flag -p

read -p "Enter your age" variable_name

Example:

#!/bin/bash echo "Enter a numner" read a echo "Enter a numner" read b var=$((a+b)) echo $var 
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Numeric Comparison logical operators

Comparison เช็ค statements evaluate เป็น true หรือ false ใช้ operators ด้านล่าง compare 2 statements:

Operation Syntax Explanation
Equality num1 -eq num2 is num1 equal to num2
Greater than equal to num1 -ge num2 is num1 greater than equal to num2
Greater than num1 -gt num2 is num1 greater than num2
Less than equal to num1 -le num2 is num1 less than equal to num2
Less than num1 -lt num2 is num1 less than num2
Not Equal to num1 -ne num2 is num1 not equal to num2

Syntax:

if [ conditions ] then commands fi

Example: เปรียบเทียบ 2 ตัวเลข หาความสัมพันธ์:

read x read y if [ $x -gt $y ] then echo X is greater than Y elif [ $x -lt $y ] then echo X is less than Y elif [ $x -eq $y ] then echo X is equal to Y fi 

Output:

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Conditional Statements (Decision Making)

Conditions = expressions evaluate เป็น boolean (true หรือ false) เช็ค conditions 用 if, if-else, if-elif-else และ nested conditionals

Structure ของ conditional statements:

  • if...then...fi statements
  • if...then...else...fi statements
  • if..elif..else..fi
  • if..then..else..if..then..fi..fi.. (Nested Conditionals)

Syntax:

if [[ condition ]] then statement elif [[ condition ]]; then statement else do this by default fi

สร้าง meaningful comparisons 用 AND -a และ OR -o

Statement นี้แปลว่า: If a greater than 40 AND b less than 6

if [ $a -gt 40 -a $b -lt 6 ]

Example: หาประเภทสามเหลี่ยมจากความยาวด้าน 3 ด้าน

read a read b read c if [ $a == $b -a $b == $c -a $a == $c ] then echo EQUILATERAL elif [ $a == $b -o $b == $c -o $a == $c ] then echo ISOSCELES else echo SCALENE fi

Output:

Test case #1

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Test case #2

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Test case #3

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Looping and skipping

For loops execute statements จำนวนครั้งเฉพาะ

Looping with numbers:

ตัวอย่าง loop iterate 5 ครั้ง

#!/bin/bash for i in {1..5} do echo $i done
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Looping with strings:

Loop ผ่าน strings ได้

#!/bin/bash for X in cyan magenta yellow do echo $X done
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

While loop

While loops check condition loop จน condition ยัง true ต้องมี counter statement increment counter ควบคุม loop execution

ตัวอย่าง (( i += 1 )) คือ counter statement increment ค่า i

Example:

#!/bin/bash i=1 while [[ $i -le 10 ]] ; do echo "$i" (( i += 1 )) done 
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Reading files

สมมติมีไฟล์ sample_file.txt ด้านล่าง:

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

อ่านไฟล์ทีละบรรทัด พิมพ์ output บนหน้าจอ

#!/bin/bash LINE=1 while read -r CURRENT_LINE do echo "$LINE: $CURRENT_LINE" ((LINE++)) done < "sample_file.txt"

Output:

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Execute commands with back ticks

ต้อง include output ของ complex command ใน script เขียน statement ใน back ticks

Syntax:

var= ` commands `

Example: อยากได้ output ของ list mountpoints ที่มี tmpfs ในชื่อ Craft statement: df -h | grep tmpfs

Include ใน bash script ใส่ใน back ticks

#!/bin/bash var=`df -h | grep tmpfs` echo $var

Output:

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

รับ arguments สำหรับ scripts จาก command line

ส่ง arguments ให้ script ตอน execute ได้

$@ แทน position ของ parameters เริ่มจาก 1

#!/bin/bash for x in $@ do echo "Entered arg is $x" done

รันแบบนี้:

./script arg1 arg2

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Automate Scripts ด้วย Cron Jobs

Cron = job scheduling utility ใน Unix-like systems Schedule jobs รันทุกวัน, ทุกสัปดาห์, ทุกเดือน หรือเวลาเฉพาะ Automation ใน Linux พึ่งพา cron jobs มาก

Syntax สำหรับ schedule crons:

# Cron job example * * * * * sh /path/to/script.sh

* แทน minute(s) hour(s) day(s) month(s) weekday(s) ตามลำดับ

ตัวอย่าง scheduling cron jobs:

SCHEDULE SCHEDULED VALUE
5 0 * 8 * At 00:05 in August.
5 4 * * 6 At 04:05 on Sunday.
0 22 * * 1-5 At 22:00 on every day-of-week from Monday through Friday.

อ่าน cron รายละเอียดใน blog post นี้

เช็ค Existing Scripts ในระบบ

Using crontab

crontab -l list scheduled scripts สำหรับ user นั้นๆ

มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

Using the find command

find command หา files จาก patterns เนื่องจาก scripts ส่วนใหญ่ลงท้าย .sh ใช้ find script:

find . -type f -name "*.sh"

Where:

  • . = current directory เปลี่ยน path ได้
  • -type f = file type ที่หาคือ text based file
  • *.sh = match files ทั้งหมดลงท้าย .sh
มาสเตอร์ Bash Shell Scripting: คู่มือผู้เริ่มต้น เขียนและอัตโนมัติ Linux Scripts

สนใจ find command รายละเอียด อ่าน post อื่นของผม

Wrapping up

ใน tutorial นี้เรียนรู้ basics ของ shell scripting ดู examples และ syntax ช่วยเขียน meaningful programs

สิ่งที่ชอบที่สุดจาก tutorial นี้คืออะไร? บอกผมบน Twitter นะครับ!

อ่าน posts อื่นของผมได้ที่นี่

Work vector created by macrovector - www.freepik.com