七、標準IO和管道 重定向I/O,為什麼要進行重定向?可以幫我們解決什麼問題? 使用管道符連接命令 1、I/O輸入輸出 顯示器是Linux系統中創建預設的輸出設備 I/O:input和output 重定向:將原本標準設備,替換為我們想要的內容 目的: 在shell腳本中對腳本輸出的內容進行處理,屏蔽 ...
七、標準IO和管道
1、I/O輸入輸出
顯示器是Linux系統中創建預設的輸出設備
I/O:input和output
-
重定向:將原本標準設備,替換為我們想要的內容
目的:
-
在shell腳本中對腳本輸出的內容進行處理,屏蔽不相關的輸出信息
-
用來清空文件或是向文件裡面寫入內容,在字元界面將所需的內容保存到指定的文件
-
-
輸出重定向:將原本輸出屏幕的內容輸出到文件
類型:
-
標準正確輸出:>:將屏幕上正確的輸出重定向到文件
-
標準錯誤輸出:2>:將屏幕上錯誤的輸出重定向到文件
-
全部輸出:&>:正確輸出和錯誤輸出
-
重定向覆蓋到文件:echo >
-
重定向追加到文件:echo >>
-
將所有不想要的輸出內容,無需重定向到文件,而是重定向到
/dev/null:Linux黑洞文件;垃圾桶;空設備;所有重定向到該文件的內容都不會被保存
-
1 [root@example tmp]# id lisi > /tmp/lisi.txt 2 id: ‘lisi’: no such user 3 [root@example tmp]# ls 4 lisi.txt zhangsan zhangsan.txt 5 [root@example tmp]# id lisi 2> /tmp/lisi.txt 6 [root@example tmp]# cat lisi.txt 7 id: ‘lisi’: no such user 8 9 [root@example tmp]# id wangwu > /tmp/wangwu.txt 2> /tmp/err.txt 10 [root@example tmp]# cat err.txt 11 id: ‘wangwu’: no such user 12 13 [root@example tmp]# id lisi &> /tmp/ok.txt 14 [root@example tmp]# cat ok.txt 15 id: ‘lisi’: no such user 16 17 [root@example tmp]# id lisi &> lisi.txt 18 [root@example tmp]# echo hello zhangsan >> lisi.txt 19 [root@example tmp]# cat lisi.txt 20 id: ‘lisi’: no such user 21 hello zhangsan
-
管道符 “ | ”
管道符的出現就是為了更好的處理Linux指令(稱之為命令的連接符號)
-
command 1| command 2:將command 1 輸出的結果(標準/正確輸出)作為command 2輸入的參數
-
1 [root@example ~]# id zhangsan | grep zhangsan 2 uid=1001(zhangsan) gid=1001(zhangsan) groups=1001(zhangsan) 3 [root@example ~]# cat /etc/passwd | grep root 4 root:x:0:0:root:/root:/bin/bash 5 operator:x:11:0:operator:/root:/sbin/nologin 6 [zhangsan@example ~]$ find / -name selinux | tee ok.txt | cat > err.txt 7 [zhangsan@example ~]$ cat err.txt 8 /sys/fs/selinux 9 /etc/sysconfig/selinux 10 /etc/selinux
-
重定向輸入:
-
使用文件作為輸入源(tr字元轉換): < 標準重定向輸入
-
-
寫入配置文件(在腳本中自動生成配置文件): <<
cat >> 文件路徑 << EOF(自定義任意字元)
文件內容……
EOF(結束符號)
1 [root@example tmp]# passwd zhangsan < pwd.txt 2 Changing password for user zhangsan. 3 New password: BAD PASSWORD: The password is shorter than 8 characters 4 Retype new password: passwd: all authentication tokens updated successfully. 5 [root@example tmp]# echo redhat | passwd --stdin zhangsan 6 Changing password for user zhangsan. 7 passwd: all authentication tokens updated successfully. 8 [root@example tmp]# cat >> err.txt <<EOF 9 > hello rhce 10 > hello wuhan 11 > EOF 12 [root@example tmp]# cat err.txt 13 hello rhce 14 hello wuhan