linux中的輸入與輸出管理(重定向輸入,輸出,管道符)

ninimino發表於2020-10-05

1 理解什麼輸入輸出的定義

1)字元裝置

字元裝置就是顯示字元到螢幕上的裝置檔案
在這裡插入圖片描述

/proc/pid/fd/
在這裡插入圖片描述在這裡插入圖片描述

2)stdin:標準輸入

編號為0
鍵盤 滑鼠 打字機

3)stdout:標準正確輸出

標號為1

4)stderr:標準錯誤輸出

標號為2

2 如何管理輸入

外界傳遞到程式中的資訊

1)< #輸入重定向

tr 'a-z' 'A-Z' < test ##把test檔案中的內容定向到tr程式中 單行錄入

在這裡插入圖片描述只是在輸出的時候顯示,但檔案裡面的內容並沒有改變

tr 'a-z' 'A-Z' < test   ###單行錄入    : 把test的內容重定向輸入到tr環境中
把原本test的預設環境shell改為指定環境  tr   (程式定向到指定環境)
tr 程式   shell 程式

==清空檔案 == >test

[westos@lzy Desktop]$ cat test
hello lzy
[westos@lzy Desktop]$ > test
[westos@lzy Desktop]$ cat test
[westos@lzy Desktop]$ 

2)<< 多行錄入

修改westos使用者的密碼為lzy

passwd westos<<EOF(字元任意)
lzy##此處的lzy不能表示為檔名稱只表示lzy字元
lzy
EOF	(當首字母再次出現表示錄入結束)

在這裡插入圖片描述

3 如何管理系統輸出

1)輸出重定向

>=1> 預設重定向輸出正確的
2>重定向輸出錯誤的
&>所有
2>&1將錯誤輸出定向到錯誤中,在管道符處理的時候可以將錯誤的一起處理

在這裡插入圖片描述

find /etc -name passwd > westos.out ##重定向正確輸出 到指定檔案
find /etc -name passwd 2> westos.out ##重定向錯誤輸出到 指定檔案
find /etc -name passwd &> westos.out ##重定向所有輸出到指定檔案

注意:重定向管理輸出後會覆蓋原檔案內容
在這裡插入圖片描述
2> /dev/null遮蔽錯誤輸出

[westos@lzy Desktop]$ find /etc -name passwd 2> /dev/null   遮蔽錯誤輸出 /dev/null 相當於垃圾桶
/etc/pam.d/passwd
/etc/passwd

2)追加

>>追加正確的輸出
2>>追加錯誤的輸出
&>>追加所有

find /etc -name passwd >> westos.out ##追加正確輸出
find /etc -name passwd 2>> westos.out ##追加錯誤輸出
find /etc -name passwd &>> westos.out ##追加所有輸出

注意:追加和重定向功能類似,但是不會覆蓋原檔案內容
在這裡插入圖片描述

3)管道 “|”

把前一條命令的輸出變成輸入傳遞到下一條命令進行操作
注意:
1.管道只處理正確輸出
在這裡插入圖片描述

2.2>&1把編號為2的輸入轉換到編號為1的輸出中

[westos@lzy Desktop]$ find /etc -name passwd 2>&1 | wc -l
16

3.tee複製輸出到指定位置
在這裡插入圖片描述

4.管道在一條命令中可以使用多次

test

在普通使用者下執行命令完成以下操作:
1.查詢/etc/下的passwd檔案遮蔽錯誤輸出
find /etc -name passwd 2> /dev/null

2.查詢/etc/下的passwd檔案正確輸出儲存到/tmp目錄中的westos.out中,錯誤輸出儲存到/tmp/目錄中的westos.err中
find /etc -name passwd > /tmp/westos.out 2> /tmp/westos.err

3.查詢/etc/下的passwd檔案儲存所有輸出到/tmp目錄中的westos.all中並統計輸入的行數
find /etc -name passwd 2>&1 | tee /tmp/westos.all | wc -l

4.查詢/etc/下的passwd檔案統計輸出行數並顯示輸出內容
[westos@lzy Desktop]$ ps
PID TTY TIME CMD
6162pts/2 00:00:00 bash
6291 pts/2 00:00:00 ps

find /etc -name passwd 2>&1 | tee /dev/pts/2 | wc -l
儲存在字元裝置中,直接在shell中顯示
5.轉換/etc/目錄中passwd檔案中的所有字母為大寫並統計檔案行數
tr 'a-z' 'A-Z' < /etc/passwd | cat -b
tr 'a-z' 'A-Z' < /etc/passwd | tee /dev/pts/2 | wc -l

7.請用指令碼非互動模式編寫檔案westos.file內容為:
hello linux
hello westos
hello linux
westos linux is very nice !!

[root@lzy ~]# vim westos.sh
[root@lzy ~]# sh westos.sh
[root@lzy ~]# cat westos.sh
cat > westos.file << EOF
hello linux
hello westos
hello linux
westos linux is very nice !!
EOF
[root@lzy ~]# cat westos.file
hello linux
hello westos
hello linux
westos linux is very nice !!
echo "hello linux
hello westos
hello linux
westos linux is very nice !!" > westos.file

相關文章