Bash Shell Scripting cơ bản: Cheatsheet lệnh và kịch bản tự động
Mục lục bài viết
1. Cấu trúc script cơ bản
```bash
#!/bin/bash
# Dòng đầu là shebang: chỉ định shell
echo "Hello, World!"
```
Phân quyền và chạy:
```bash
chmod +x myscript.sh
./myscript.sh
bash myscript.sh
```
Comment: # Đây là comment
Exit code: exit 0 (thành công), exit 1 (lỗi).
Xem: echo $?
2. Biến và kiểu dữ liệu
```bash
# Gán biến (không có khoảng trắng quanh =)
name="Alice"
age=25
readonly PI=3.14 # Không thể gán lại
# Dùng biến
echo "Hello, $name"
echo "Age: ${age}" # Dùng {} để phân cách
# Biến mặc định
: ${USER:=\"default\"}
echo ${USER}
# Biến đặc biệt
echo "Script: $0, Args: $1 $2, Tổng: $#, PID: $$"
# Command substitution
now=$(date)
echo "Now: $now"
# Arithmetic
sum=$((5 + 3))
echo "Sum: $sum"
```
3. Điều kiện (if/else)
```bash
# Cú pháp
if [ \"$age\" -gt 18 ]; then
echo "Adult"
elif [ \"$age\" -eq 18 ]; then
echo "Exactly 18"
else
echo "Under 18"
fi
# So sánh số: -eq, -ne, -gt, -ge, -lt, -le
# So sánh chuỗi: =, !=, -z (rỗng), -n (không rỗng)
# File test: -f (file), -d (dir), -e (exist), -x (executable)
# Kiểm tra file
if [ -f \"/etc/passwd\" ]; then
echo "File tồn tại"
fi
# Kết hợp điều kiện
if [ \"$name\" = \"Alice\" ] && [ \"$age\" -gt 20 ]; then
echo "Alice > 20"
fi
# Case statement
case \"$1\" in
start) echo "Starting...";;
stop) echo "Stopping...";;
*) echo "Usage: $0 {start|stop}"; exit 1;;
esac
```
4. Vòng lặp
```bash
# For loop với danh sách
for fruit in apple banana cherry; do
echo "I like $fruit"
done
# C-style for
for ((i=0; i<10; i++)); do
echo "Count: $i"
done
# While loop
count=0
while [ \"$count\" -lt 5 ]; do
echo "Count: $((count++))"
done
# While đọc file
while IFS= read -r line; do
echo "Line: $line"
done < \"input.txt\"
# Until loop
until [ -f \"/tmp/done\" ]; do
sleep 1
done
# Break và Continue
for i in {1..10}; do
[ $i -eq 5 ] && continue
[ $i -eq 8 ] && break
echo $i
done
```
5. Hàm (Functions)
```bash
# Định nghĩa hàm
greet() {
local name=$1 # local: biến cục bộ
echo "Hello, $name!"
return 0
}
# Gọi hàm
greet \"World\"
# Hàm trả về giá trị
get_sum() {
echo $(( $1 + $2 ))
}
result=$(get_sum 5 3)
echo "Result: $result"
# Source file khác
source \"./helpers.sh\"
# Hoặc
. ./helpers.sh
# Trap (bắt tín hiệu)
trap 'echo "Ctrl+C pressed"; cleanup; exit' SIGINT
trap 'echo "Script ending"' EXIT
```
6. Xử lý văn bản và file
```bash
# Grep các pattern
grep \"error\" log.txt
grep -i \"warning\" log.txt # Không phân biệt hoa thường
grep -r \"TODO\" . # Đệ quy
# Sed: thay thế văn bản
sed -i 's/old/new/g' file.txt
sed -n '10,20p' file.txt # In dòng 10-20
# Awk: xử lý cột
awk '{print $1, $3}' file.txt
awk -F: '{print $1}' /etc/passwd
# Find: tìm file
find . -name \"*.log\" -mtime +7 -delete
find /var/log -type f -size +100M
# Xử lý JSON với jq
cat data.json | jq '.users[].name'
# Xử lý CSV với cut và sort
cut -d, -f2 data.csv | sort | uniq -c | sort -rn
shellcheck để kiểm tra lỗi script: shellcheck myscript.sh. Cài bằng apt install shellcheck hoặc brew install shellcheck.🙋 Câu hỏi thường gặp
Sự khác nhau giữa [ ] và [[ ]] trong Bash?
[[ ]] là từ khoá Bash (mới hơn): hỗ trợ pattern matching, regex, không cần escape. [ ] là command test (POSIX): portable cho mọi shell. Dùng [[ ]] trong Bash, [ ] nếu cần POSIX compat.
Làm sao debug Bash script?
Chạy với bash -x myscript.sh: hiển thị từng dòng lệnh. Hoặc thêm set -x trong script để bật debug, set +x để tắt. set -e: dừng script nếu lệnh fail.