Search Suggest

Shell - IO Redirections and Pipes


Theo mặc định của shell, khi thực hiện một command thì nó sẽ lấy dữ liệu đầu vào (nếu có) từ standard input (stdin) và xuất kết quả ra standard output (stdout). Tuy nhiên shell cũng cung cấp cú pháp để có thể thay thế stdin và stdout bằng đối tượng khác đó chính là file.


1. Output Redirection
Syntax:
 $ command > filename   
Xuất kết quả và ghi vào filename (nếu filename chưa có thì tạo mới)

 $ command >> filename  
Tương tự như trên, nhưng ghi tiếp (append) vào filename nếu filename đã tồn tại và có nội dung khác trước đó.

Ex:
 [ninhld@localhost ex]$ date > time.txt  
[ninhld@localhost ex]$ cat time.txt
Sun Jul 12 21:46:04 ICT 2015
[ninhld@localhost ex]$
[ninhld@localhost ex]$
[ninhld@localhost ex]$ uptime >> time.txt
[ninhld@localhost ex]$ cat time.txt
Sun Jul 12 21:46:04 ICT 2015
21:46:24 up 3:03, 3 users, load average: 0.38, 0.56, 0.64


2. Input Redirection
Syntax:
 $ command < filename   
Ngược lại với Output Redirection.

Ex:
 [ninhld@localhost ex]$ more < time.txt   
Sun Jul 12 21:46:04 ICT 2015
21:46:24 up 3:03, 3 users, load average: 0.38, 0.56, 0.64

3. Discard the output
Khi không muốn xuất kết quả hoặc các thông báo lỗi ra màn hình, shell cung cấp cú pháp để loại bỏ các kết quả và thông báo lỗi như sau.

Syntax:
 $ command > /dev/null         #Discard stdout   
$ command > /dev/null 2>&1 #Discard stdout and stderr
Trong đó /dev/null là một device file đặc biệt, tất cả các luồng dữ liệu đi vào nó đều được loại bỏ.

Ex:
 $ date > /dev/null  
$ date > /dev/null 2>&1
Bạn sẽ không có gì được print trên terminal.

4. Redirection Commands
Bảng dưới đây liệt kê tất cả các cú pháp redirection commands, bao gồm các cúa pháp đã liệt kê ở các mục trên.


Command Description
pgm > file Output of pgm is redirected to file
pgm < file Program pgm reads its input from file.
pgm >> file Output of pgm is appended to file.
n > file Output from stream with descriptor n redirected to file.
n >> file Output from stream with descriptor n appended to file.
n >& m Merge output from stream n with stream m.
n <& m Merge input from stream n with stream m.
<< tag Standard input comes from here through next tag at start of line.
| Takes output from one program, or process, and sends it to another.

5. Pipes
Pipes là đường ống dùng để truyền kết quả từ đầu ra của một lệnh vào đầu vào của một lệnh khác được thực hiện sau. Ký hiệu của pipe là dấu gạch đứng.

Ex:
 $ ls /dev | grep "fb"  
fb0

Lệnh ls /dev liệt kê ra danh sách tất cả các device file nằm trong thư mục /dev, kết quả này lại là đầu vào của lệnh grep (lệnh tìm kiếm theo mẫu) thông qua pipe, kết quả của chuỗi lệnh trên là lọc ra được "fb0" tương ứng với /dev/fb0.


إرسال تعليق