Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

I/O 重定向與管線完整講解

一、標準輸入與輸出

程式 = 指令 + 資料,資料又分為 input 與 output。Linux 為程式提供三種 I/O 通道:

標準輸入 stdin   0   預設接收來自鍵盤的輸入
標準輸出 stdout  1   預設輸出到終端
標準錯誤 stderr  2   預設輸出到終端

二、輸出重定向

(1)覆蓋重定向 >

command > /path/to/file

[root@localhost testdir]# cat a > a1      # a1 原內容被覆蓋

(2)追加重定向 >>

command >> /path/to/file

[root@localhost testdir]# cat /etc/issue >> a1
[root@localhost testdir]# cat a1
hello world!
CentOS release 6.8 (Final)
Kernel \r on an \m

(3)錯誤輸出重定向

command 2>  /path/to/file    覆蓋
command 2>> /path/to/file    追加

(4)標準輸出與錯誤輸出合併

command &>  /path/to/file
command &>> /path/to/file
command >  /path/to/file 2>&1
command >> /path/to/file 2>&1

[root@localhost testdir]# cat /etc/issue /etc/abc &> f1
[root@localhost testdir]# cat f1
CentOS release 6.8 (Final)                  # 正確輸出
cat: /etc/abc: No such file or directory    # 錯誤輸出

(5)以 heredoc 取代鍵盤輸入

[root@localhost testdir]# cat < catfile <

寄一封求助信給 zhang:

[root@localhost testdir]# mail -s "help" zhang <

(6)tr:轉換與刪除字元

tr [-ds] SET1
-d  刪除 SET1 中的字元
-s  把連續重複的字元壓縮為單一個
# 把 last 輸出中的小寫轉大寫
[root@centos7 ~]# last | tr [a-z] [A-Z]

# 刪除 /etc/passwd 中的冒號
[root@localhost testdir]# cat /etc/passwd | tr -d ':'
rootx00root/root/bin/bash
binx11bin/bin/sbin/nologin

# /root 檔案列表合併成一行
[root@centos7 /]# ls -a /root | tr '\n' ' '

三、管線

command1 | command2 | command3

注意三點:每個管線後接的第一個元件必須是命令(如 less、more、head、tail);管線命令必須處理 standard output,對 standard error 則視而不見;管線命令必須能接收前一命令的輸出作為自己的 standard input。

cut:擷取欄位

cut -d '分隔字元' -f N   依分隔字元切段後取出第 N 段
cut -c 字元範圍           以字元為單位擷取

[root@centos7 /]# echo $PATH | cut -d: -f 3
/usr/sbin

tee:同時輸出到螢幕與檔案

command1 | tee file | command2

[root@centos7 /]# who | tee f4 | tr 'a-z' 'A-Z'
ZHANG   :0      2016-07-30 12:50 (:0)
ROOT    PTS/1   2016-07-30 16:04 (10.1.250.64)

tee 適合用來保存不同階段的輸出、排查複雜管線的問題,或同時查看與記錄結果。

本文出自「zhang1003995416」博客,請務必保留此出處 https://1003995416.blog.51cto.com/10482168/1832136

Copyright © Linux教程網 All Rights Reserved