How to redirect stderr and stdout to a file
การจัดการ output ใน linux ไม่ใช่เรื่องที่ไกลตัว เนื่องจากบ่อยครั้งที่เราจะเห็นคำสั่งต่างๆ มีการ redirect error และ output ไปยังไฟล์ เพื่อทำการจัดเก็บและสามารถนำไปตรวจสอบได้ภายหลัง โดยเฉพาะอย่างยิ่งคำสั่งหรือโปรแกรมที่เมื่อรันแล้วมีการแสดงข้อมูลมากทำให้เราไม่สามารถอ่านได้ทันจำเป็นต้องทำการ redirect ไปเก็บไว้ยังไฟล์ เพื่อที่เราจะสามารถเปิดอ่านข้อมูลของการทำงานได้อย่างครบถ้วน บทความนี้เราจะมาพูดถึงเรื่องของการจัดการ output และ error ในขณะที่ได้มีการรันคำสั่ง
Bash shell ของ Linux จะมีรูปแบบการรับและส่งข้อมูลด้วยกัน 3 ประเภทด้วยกัน คือ
- stdin (standard input) – เป็นการรับข้อมูลของโปรแกรม เช่นการรับข้อมูลผ่าน keyboard
- stdout (standard output) – ส่งข้อมูลออกหน้าจอ
- stderr (standard error) – ส่งข้อมูล error ออกหน้าจอ
ทั้ง 3 ประเภท สามารถแทนด้วยตัวเลขได้ดังนี้
- 0 = stdin (standard input)
- 1 = stdout (standard output)
- 2 = stderr (standard error)
* สำหรับการ redirect ทั้ง stdout และ stderr เราจะใช้ตัว “&” ซึ่ง operator ตัวนี้สามารถใช้ได้ตั้งแต่ Bash 4 เป็นต้นไป
ตัวอย่างการใช้งาน
- ต้องการ redirect error message ไปยังไฟล์ error.log ในขณะที่รันโปรแกรมหรือคำสั่ง[shell][tum@Ezylinux ~]$ program-name 2> error.log
[tum@Ezylinux ~]$ command 2> error.log[/shell] - ต้องการ redirect stderr ไปยัง stdout[shell][tum@Ezylinux ~]$ command 2>&1[/shell]
- ต้องการ redirect error message ไปยังไฟล์ error.log และ output ไปยังไฟล์ output.log ในขณะที่รันโปรแกรมหรือคำสั่ง
[shell][tum@Ezylinux ~]$ program-name 1>out.log 2>err.log[/shell] - ต้องการ redirect error message และ output ไปยังไฟล์ out.log ในขณะที่รันโปรแกรมหรือคำสั่ง[shell][tum@Ezylinux ~]$ command &> out.log[/shell]
หรือ
[shell][tum@Ezylinux ~]$ command 2>&1 >out.log [/shell]