How to redirect stdout and stderr to log file
วิธีการ redirect standard output และ standard error ไปเก็บไว้ยัง log file
การ redirect stdout and stderr ไปยัง log file ที่ถูกต้อง
1 2 3 |
command > /path/to/log 2>&1 |
ระบบจะทำการ redirect stdout ไปยัง log file และพร้อมกับ redirect stderr ไปยัง stdout ซึ่งส่งผลให้ทั้ง stdout และ stderr ถูก redirect เข้า log file
ตัวอย่างเช่น
ทดสอบการ redirect ด้วยคำสั่ง ls -l
1 2 3 |
[tum@ezylinux test]$ ls -l > log2 2>&1 |
ตรวจสอบข้อมูลข้างในพบว่ามีข้อมูลที่ได้ redirect ไป
1 2 3 4 5 |
[tum@ezylinux test]$ cat log2 total 0 -rw-rw-r-- 1 t1sb t1sb 0 Nov 3 17:02 log2 |
ทดสอบการ redirect ด้วยคำสั่ง lss -l (ตั้งใจให้เกิด error)
1 2 3 |
[tum@ezylinux test]$ lss -l > log2 2>&1 |
ตรวจสอบข้อมูลข้างในพบว่ามีข้อมูล error ที่ได้ redirect ไป
1 2 3 4 |
[tum@ezylinux test]$ cat log2 -bash: lss: command not found |
การ redirect stdout and stderr ไปยัง log file ที่ผิด
1 2 3 |
command 2>&1 > /path/to/log |
ระบบจะทำการ redirect stderr ไปยัง stdout ที่จะส่งผลลัพธ์ออก console และ stdout ที่ได้ทำการ redirect จะส่งเข้าไปยัง log file ซึ่งส่งผลให้เมื่อเกิด error ขึ้นจะถูกแสดงออกที่หน้า console ส่วนผลลัพธ์จะถูก redirect เข้า log file
ทดสอบการ redirect ด้วยคำสั่ง ls -l
1 2 3 |
[tum@ezylinux test]$ ls -l 2>&1 > log2 |
ตรวจสอบข้อมูลข้างในพบว่ามีข้อมูลที่ได้ redirect ไป
1 2 3 4 5 |
[tum@ezylinux test]$ cat log2 total 0 -rw-rw-r-- 1 t1sb t1sb 0 Nov 3 17:00 log2 |
ทดสอบการ redirect ด้วยคำสั่ง lss -l (ตั้งใจให้เกิด error) จะพบ error ถูกส่งออกมายัง console แทนที่จะถูกส่งเข้าไฟล์
1 2 3 4 |
[tum@ezylinux test]$ lss -l 2>&1 > log2 -bash: lss: command not found |
ตรวจสอบข้อมูลข้างในพบว่ามีข้อมูล error ที่ได้ redirect ไป จะไม่พบ error อะไรเลย
1 2 3 |
[tum@ezylinux test]$ cat log2 |