คู่มือนี้สอนใช้ nohup รันคำสั่ง/สคริปต์ใน Background ค้างไว้แม้ Logout/Disconnect SSH
nohup คืออะไร?
- No Hang Up - ไม่สนใจ SIGHUP Signal (ส่งเมื่อ Terminal ปิด/Logout)
- ทำให้ Process ทำงานต่อไปได้แม้ User ออกจากระบบ
- Output ถูก Redirect ไป
nohup.outอัตโนมัติ
Syntax พื้นฐาน
nohup command [args] &
&- รันใน Background (Job Control)- หรือใช้
nohup command > output.log 2>&1 &ระบุไฟล์ Log เอง
ตัวอย่าง: Backup MySQL ใหญ่
# 1. SSH เข้าเซิร์ฟเวอร์
ssh user@server
# 2. รัน mysqldump ด้วย nohup
nohup mysqldump -u user -p'password' large_db > large_db.sql &
# Output:
# [1] 12345
# nohup: appending output to 'nohup.out'
ตรวจสอบ Process
# ดู PID จาก output (12345)
ps -ef | grep 12345
# หรือดู Jobs ของ Shell
jobs
# [1]+ Running nohup mysqldump ...
# ดู Output จริง
tail -f nohup.out
เมื่อ Process เสร็จ
[1]+ Done nohup mysqldump -u user -p'password' large_db > large_db.sql
ตรวจสอบ nohup.out สำหรับ Error/Warning
เทคนิคขั้นสูง
| เทคนิค | คำสั่ง | คำอธิบาย |
|---|---|---|
| Disown | command & disown -h %1 | แยก Job จาก Shell (ไม่ได้รับ SIGHUP) |
| Screen | screen -S backup | Terminal Multiplexer - Detach/Attach ได้ |
| Tmux | tmux new -s backup | Screen ตัวใหม่ ทรงพลังกว่า |
| Systemd Service | systemd-run --user command | จัดการเป็น Service พร้อม Logging/Restart |
| At/Batch | at now + 1 hour < script.sh | Schedule รันภายหลัง |
| Tool | เหมาะสำหรับ | ความยาก |
|---|---|---|
| nohup & | Command เดียว ใช้ครั้งคราว | ง่าย |
| Screen/Tmux | Interactive, หลายหน้าต่าง, Resume ได้ | ปานกลาง |
| Systemd | Production Service, Auto-restart, Logging | สูง |