一、重定向符號:> >> 1> 1>> 2> 2>> < <<
1.標準輸出重定向: >與1>
[root@NSW ~]# ls anaconda-ks.cfg install.log.syslog [root@NSW ~]# echo My name is NSW>nsw.txt [root@NSW ~]# cat nsw.txt My name is NSW
//新建nsw.txt,並將>左邊的字符寫入到文件中。目錄下無文件,自動創建文件。
1>
[root@NSW ~]# echo My name is NSW 1>test.txt
[root@NSW ~]# cat test.txt
My name is NSW
//同理。
[root@NSW ~]# cat nsw.txt
My name is NSW
[root@NSW ~]# echo I love oldboy >nsw.txt
[root@NSW ~]# cat nsw.txt
I love oldboy
//可以看出>會將源文件的內容覆蓋。(謹慎)
[root@NSW ~]# echo Welcome 1>nsw.txt
[root@NSW ~]# cat nsw.txt
Welcome
//1>同樣也會先覆蓋原文件的內容。
小結:重定向符>和1>都爲輸出重定向;
被輸入的文件有則直接輸入,無則自動創建該文件並輸入;
將符號左邊的字符串輸入到右邊文件中且覆蓋原文件。
2.追加輸出重定向:>> 1>>
[root@NSW ~]# ls
anaconda-ks.cfg install.log.syslog nsw.txt test.txt
[root@NSW ~]# cat nsw.txt
Welcome
[root@NSW ~]# echo My name is nsw>>nsw.txt
[root@NSW ~]# cat nsw.txt
Welcome
My name is nsw
//可以看出確實在雲文件最後面新追加了My name is nsw沒有覆蓋源文件。
[root@NSW ~]# echo My name is nsw1>>nsw.txt
[root@NSW ~]# cat nsw.txt
Welcome
My name is nsw
My name is nsw1
//這需要注意的是符號左面需要空一格要不繫統會認爲1是輸入的字符。
[root@NSW ~]# echo My name is nsw 1>>nsw.txt
[root@NSW ~]# cat nsw.txt
Welcome
My name is nsw
My name is nsw1
My name is nsw
//同理1>>和>>作用相同。
[root@NSW ~]# ls
anaconda-ks.cfg install.log.syslog nsw.txt test.txt
[root@NSW ~]# echo Hello >>hello.txt
[root@NSW ~]# cat hello.txt
Hello
[root@NSW ~]# cat HELLO.txt
HELLO
小結:追加輸出重定向>>和1>>,將內容追加到指定文件中最後一行的下一行,不會覆蓋源文件;
指定目錄下有源文件直接追加,沒有則自定創建文件並追加內容。
3.標準錯誤重定向2>
[root@NSW ~]# cat hello.txt
Hello
[root@NSW ~]# eho test
-bash: eho: command not found
[root@NSW ~]# eho test 2>hello.txt
[root@NSW ~]# cat hello.txt
-bash: eho: command not found
//將錯誤重定向到指定文件中並覆蓋原文件內容。
4.錯誤追加重定向2>>
[root@NSW ~]# cat test.txt
My name is NSW
[root@NSW ~]# eho Hello 2>> test.txt
[root@NSW ~]# cat test.txt
My name is NSW
-bash: eho: command not found
//將錯誤追加到指定文件中。
[root@NSW ~]# ls
anaconda-ks.cfg install.log.syslog
[root@NSW ~]# eho hello 2>test.txt
[root@NSW ~]# cat test.txt
-bash: eho: command not found
[root@NSW ~]#
[root@NSW ~]#
[root@NSW ~]# eho hello 2>>test.txt
[root@NSW ~]# cat test.txt
-bash: eho: command not found
-bash: eho: command not found
//無論2>還是2>>在目錄下沒有指定文件時都會自動創建文件。
小結:標準錯誤輸出重定向和錯誤追加重定向都是將執行錯誤的提示內容放入指定文件中,故障排查,區別在於一個是覆蓋一個是追加。
5.標準輸入重定向:<
[root@NSW ~]# echo 1 2 3 4 5 6 >test.txt
[root@NSW ~]# cat test.txt
1 2 3 4 5 6
[root@NSW ~]# xargs -n2 test.txt
^C
[root@NSW ~]# xargs -n2 <test.txt
1 2
3 4
5 6
//用來將<右側文件中的內容輸出給左側的命令,可以使用<符號的命令很少,xargs爲其中之一。
6.追加輸入重定向:<<
[root@NSW ~]# ls
anaconda-ks.cfg install.log.syslog test.txt
[root@NSW ~]# cat >>nsw.txt<<EOF
> Hello!
> My name is NSW
> EOF
[root@NSW ~]# cat nsw.txt
Hello!
My name is NSW
//將多行內容追加輸入到指定文件中,指定目錄下沒有文件則新建。
小結:<是用來將符號右側文本的內容作爲左側命令的執行條件;
<<是方便輸入多行內容到指定文件中。
==============================================================
如果文中有錯誤的地方歡迎大家指出,謝謝!