สารบัญ
- Prerequisites
- Introduction
- Definition of Bash scripting
- Advantages of Bash scripting
- Overview of Bash shell and CLI
- How to Get Started with Bash Scripting
- How to Run Bash Commands from Command Line
- How to Create and Execute Bash Scripts
- Bash Scripting Basics
- Comments in bash scripting
- Variables and data types in Bash
- Input and output in Bash scripts
- Basic Bash commands (echo, read, etc.)
- Conditional statements (if/else)
- Looping and Branching in Bash
- While loop
- For loop
- Case statements
- How to Schedule Scripts using cron
- How to Debug and Troubleshoot Bash Scripts
- Conclusion
- 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 directoryls- list directory contentsecho- print text หรือ variable valueman- ดู 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
- ขึ้นต้นตัวอักษหรือ underscore
- ประกอบด้วย letters, numbers, underscores
- Case-sensitive
- ไม่มี spaces หรือ special characters
- ใช้ชื่อ descriptive
- หลีกเลี่ยง reserved keywords (if, then, else, fi, etc.)
Input and Output in Bash scripts
Gathering input
- Read user input:
read entered_name - Read from file:
while read line; do echo $line; done < input.txt - Command line arguments:
$1,$2... (echo "Hello, $1!")
Displaying output
- Print terminal:
echo "Hello, World!" - Write to file:
echo "text" > output.txt(overwrite) - Append to file:
echo "more" >> output.txt - 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)
| Schedule | Description | Example |
|---|---|---|
0 0 * * * | ทุกวันเที่ยงคืน | 0 0 * * * /path/to/script.sh |
*/5 * * * * | ทุก 5 นาที | */5 * * * * /path/to/script.sh |
0 6 * * 1-5 | 6 โมงเช้าจันทร์-ศุกร์ | 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