Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

วิธีบันทึก Output ของคำสั่ง Linux ลงไฟล์

คู่มือนี้สอนวิธี Redirect Output ของคำสั่ง Linux ไปยังไฟล์ เพื่อเก็บ Log, รายงาน หรือ Debug

Redirection Operators พื้นฐาน

ตัวอย่างการใช้งาน

# เขียนทับไฟล์
ls /var/log > /tmp/varlog.log

# ต่อท้ายไฟล์
ls /var/log >> /tmp/varlog.log

# บันทึกทั้ง Output และ Error
command &> /tmp/output.log
command &>> /tmp/output.log

# แยก Output และ Error
command > /tmp/out.log 2> /tmp/err.log

# ไปพร้อมกัน stdout ไปไฟล์ stderr ไป terminal
command > /tmp/out.log

คำสั่ง logsave (Alternative)

# logsave /tmp/varlog.log ls /var/log
# logsave -a /tmp/varlog.log ls /var/log   # append mode
  • เพิ่ม Timestamp อัตโนมัติ
  • Output สะอาดกว่า Redirection ธรรมดา
  • มีในแพ็กเกจ e2fsprogs (มาติดตั้งพร้อม Linux ทุกตัว)

Tee - แสดงหน้าจอและบันทึกไฟล์พร้อมกัน

# แสดงหน้าจอ + เขียนทับไฟลー
command | tee /tmp/output.log

# แสดงหน้าจอ + ต่อท้ายไฟล์
command | tee -a /tmp/output.log

# รวม stderr ด้วย
command 2>&1 | tee /tmp/output.log

การใช้งานใน Shell Script

#!/bin/bash
LOG_FILE="/var/log/my-script-$(date +%F).log"

exec > >(tee -a "$LOG_FILE")
exec 2>&1

echo "Script started at $(date)"
# ... คำสั่งต่างๆ ...
echo "Script finished at $(date)"

Best Practices

  • ใช้ >> (Append) สำหรับ Log file เพื่อไม่สูญหายข้อมูลเก่า
  • ใช้ 2>&1 หรือ &> เพื่อจับ Error ด้วย
  • ตั้งชื่อไฟล์ Log ให้มีวันที่: backup-$(date +%F).log
  • ตั้งค่า Logrotate สำหรับไฟล์ Log ที่ใหญ่ขึ้นเรื่อยๆ

การ Redirect Output เป็นทักษะพื้นฐานที่จำเป็นสำหรับการเขียน Script, Automation และ Troubleshooting

Operatorชื่อคำอธิบาย
>Output Redirectionเขียนทับไฟล์ (Overwrite) สร้างใหม่หากไม่มี
>>Append Redirectionต่อท้ายไฟล์ (Append) สร้างใหม่หากไม่มี
2>Stderr RedirectionRedirect เฉพาะ Standard Error
2>>Stderr Appendต่อท้าย Standard Error
&> หรือ >&Both Stdout+StderrRedirect ทั้ง stdout และ stderr (Overwrite)
&>>Both Appendต่อท้ายทั้ง stdout และ stderr