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

เชี่ยวชาญ Bash Scripting: คู่มือสำหรับผู้เริ่มต้นสู่ Linux Shell Automation

สารบัญ

  1. Prerequisites
  2. Introduction
  3. Definition of Bash scripting
  4. Advantages of Bash scripting
  5. Overview of Bash shell and CLI
  6. How to Get Started with Bash Scripting
  7. How to Run Bash Commands from Command Line
  8. How to Create and Execute Bash Scripts
  9. Bash Scripting Basics
  10. Comments in bash scripting
  11. Variables and data types in Bash
  12. Input and output in Bash scripts
  13. Basic Bash commands (echo, read, etc.)
  14. Conditional statements (if/else)
  15. Looping and Branching in Bash
  16. While loop
  17. For loop
  18. Case statements
  19. How to Schedule Scripts using cron
  20. How to Debug and Troubleshoot Bash Scripts
  21. Conclusion
  22. Resources for learning more

Prerequisites

  • Linux ที่รันอยู่พร้อม command line access

ถ้าไม่มี Linux หรือเพิ่งเริ่มต้น ใช้ Replit (browser-based IDE) เข้าถึง bash shell ได้ในไม่กี่นาที หรือติดตั้ง Linux บน Windows ผ่าน WSL

Introduction

Definition of Bash scripting

Bash script คือไฟล์ที่มีลำดับคำสั่ง ที่ถูก execute โดย bash program บรรทัดต่อบรรทัด ทำให้ทำ sequence ของ actions ได้ เช่น navigate ไป directory, สร้าง folder, launch process ผ่าน command line บันทึกคำสั่งใน script จะทำซ้ำ sequence เดียวกันหลายครั้งได้โดยรัน script

Advantages of Bash scripting

  • Automation: ทำงานซ้ำๆ อัตโนมัติ ประหยัดเวลา ลด error จาก manual execution
  • Portability: รันบน Unix, Linux, macOS, Windows (ผ่าน emulator/VM)
  • Flexibility: ปรับแต่งได้ง่าย รวมกับภาษาอื่น/ utilities ได้
  • Accessibility: เขียนง่าย ไม่ต้องใช้ tools พิเศษ edit ด้วย text editor ใดก็ได้ shell interpreter มี built-in
  • Integration: รวมกับ databases, web servers, cloud services ได้
  • Debugging: debug ง่าย shell มี built-in debugging/error-reporting tools

Overview of Bash shell and CLI

"Shell" และ "Bash" ใช้สลับกันได้ แต่ต่างกันเล็กน้อย Shell = โปรแกรมให้ CLI สำหรับ interact กับ OS Bash (Bourne-Again SHell) = shell ยอดนิยม default ในหลาย Linux distros

Shell prompt ตัวอย่าง: zaira@Zaira:~/shell-tutorial$ รอคำสั่ง user Root prompt: [root@host ~]#

Shell อื่นๆ: Korn shell (ksh), C shell (csh), Z shell (zsh) แต่ละตัว syntax และ features ต่างกัน แต่เป้าหมายเดียวกัน: CLI สำหรับ OS

เช็ค shell type: ps

How to Get Started

Running Bash commands from command line

Shell prompt: [username@host ~]$ พิมพ์คำสั่งหลัง $

Syntax: command [OPTIONS] arguments

Basic commands:

  • date - แสดงวันที่
  • pwd - แสดง current directory
  • ls - list directory contents
  • echo - print text หรือ variable value
  • man - ดู manual ของคำสั่ง

How to Create and Execute Bash Scripts

Script naming conventions

โดย convention bash scripts ลงท้าย .sh แต่รันได้แม้ไม่มี extension

Adding the Shebang

บรรทัดแรกต้องเป็น shebang: #!/bin/bash บอก shell ให้ execute via bash หา path ได้ด้วย which bash

Creating first bash script

สร้าง run_all.sh:

#!/bin/bash
echo "Today is " `date`
echo -e "\nenter the path to directory"
read the_path
echo -e "\n you path has the following files and folders: "
ls $the_path

อธิบายบรรทัดต่อบรรทัด: shebang, echo date, prompt user input, read เก็บใน variable, ls แสดงไฟล์

Executing the bash script

chmod u+x run_all.sh

chmod เปลี่ยน ownership u = user +x = add execute permission

รันได้ 3 วิธี: sh run_all.sh, bash run_all.sh, ./run_all.sh

Bash Scripting Basics

Comments

ขึ้นต้นด้วย # จะถูก interpreter ignore ดีสำหรับ documentation

Variables and data types in Bash

Variables เก็บข้อมูล ไม่มี data types เก็บ numeric, characters, strings ได้

Set variable: country=Pakistan หรือ same_country=$country เข้าถึง: $country

Variable naming conventions

  1. ขึ้นต้นตัวอักษหรือ underscore
  2. ประกอบด้วย letters, numbers, underscores
  3. Case-sensitive
  4. ไม่มี spaces หรือ special characters
  5. ใช้ชื่อ descriptive
  6. หลีกเลี่ยง reserved keywords (if, then, else, fi, etc.)

Input and Output in Bash scripts

Gathering input

  1. Read user input: read entered_name
  2. Read from file: while read line; do echo $line; done < input.txt
  3. Command line arguments: $1, $2... (echo "Hello, $1!")

Displaying output

  1. Print terminal: echo "Hello, World!"
  2. Write to file: echo "text" > output.txt (overwrite)
  3. Append to file: echo "more" >> output.txt
  4. Redirect output: ls > files.txt

Basic Bash commands

cd, ls, mkdir, touch, rm, cp, mv, echo, cat, grep, chmod, sudo, df, history, ps

Conditional statements (if/else)

Syntax:

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

Logical operators: AND -a, OR -o

ตัวอย่าง: รับตัวเลข ตรวจสอบ positive/negative/zero

Looping and Branching

While loop

i=1
while [[ $i -le 10 ]]; do
    echo "$i"
    (( i += 1 ))
done

For loop

for i in {1..5}; do
    echo $i
done

Case statements

case expression in
    pattern1) code ;; 
    pattern2) code ;;
    *) default code ;;
esac

ตัวอย่าง: fruit="apple" -> "This is a red fruit."

How to Schedule Scripts using cron

Cron = job scheduling utility ใน Unix-like systems ตั้งค่า daily, weekly, monthly, specific time

Syntax: * * * * * sh /path/to/script.sh (minute hour day month weekday)

ScheduleDescriptionExample
0 0 * * *ทุกวันเที่ยงคืน0 0 * * * /path/to/script.sh
*/5 * * * *ทุก 5 นาที*/5 * * * * /path/to/script.sh
0 6 * * 1-56 โมงเช้าจันทร์-ศุกร์0 6 * * 1-5 /path/to/script.sh
0 0 1-7 * *วันที่ 1-7 ทุกเดือน0 0 1-7 * * /path/to/script.sh
0 12 1 * *วันที่ 1 ทุกเดือนเที่ยงวัน0 12 1 * * /path/to/script.sh

crontab -l list jobs, crontab -e add/edit

How to Debug and Troubleshoot Bash Scripts

1. Set set -x option

Enable debug mode พิมพ์ทุกคำสั่งที่ execute พร้อม + sign

2. Check exit code

$? = exit code ล่าสุด 0 = success, อื่นๆ = error

3. Use echo statements

Insert echo ทั่วโปรแกรมเพื่อดูค่า variables และ flow

4. Use set -e option

Exit ทันทีเมื่อคำสั่งใด fail

5. Troubleshooting crons ด้วย logs

Ubuntu/Debian: /var/log/syslog ตรวจสอบว่า job รันตามตารางหรือไม่

Conclusion

บทความนี้ครอบคลุม: เข้าถึง terminal, basic commands, bash shell, loops, conditionals, cron automation, troubleshooting techniques

Resources: คอร์ส Linux 6 ชั่วโมงบน freeCodeCamp