快速入門Shell編程(五)輸入輸出重定向
重定向作用
一個進程默認會打開標準輸入、標準輸出、錯誤輸出三個文件描述符。
重定向可以讓我們的程序的標準輸出、錯誤輸出的信息重定向文件里,那么這里還可以將文件的內容代替鍵盤作為一種標準輸入的方式。
重定向符號
輸入重定向符號"<"
輸出重定向符號">",">>","2>","&>"
輸入重定向功能
會把文件的內容當做參數輸入到進程,如下例子:
[root@omp120 home]# cat file.txt hello [root@omp120 home]# read a < file.txt [root@omp120 home]# echo $a hello
1
2
3
4
5
file.txt文件的內容是hello,上述的例子就是把file.txt的內容重定向到a這個變量,并把a變量打印出來。
輸出重定向功能
會把文件內容清空,在把輸出內容重定向到指定的文件里,并且如果文件不存在則創建,如下例子:
[root@lincoding tmp]# echo 123 > /tmp/test [root@lincoding tmp]# cat /tmp/test 123 [root@lincoding tmp]# echo abc > /tmp/test [root@lincoding tmp]# cat /tmp/test abc
1
2
3
4
5
6
會把輸出的內容追加到指定的文件里,該文件不會被清空,并且如果文件不存在則創建,如下例子:
[root@lincoding tmp]# echo 123 >> /tmp/test [root@lincoding tmp]# cat /tmp/test 123 [root@lincoding tmp]# echo abc >> /tmp/test [root@lincoding tmp]# cat /tmp/test 123 abc
1
2
3
4
5
6
7
是把進程錯誤輸出的內容重定向到指定的文件里,如下例子:
[root@lincoding home]# abc -bash: abc: command not found [root@lincoding home]# abc > error.txt -bash: abc: command not found [root@lincoding home]# cat error.txt [root@lincoding home]# [root@lincoding home]# abc 2> error.txt [root@lincoding home]# cat error.txt -bash: abc: command not found
1
2
3
4
5
6
7
8
9
以上的演示結果可以得知,abc不是Linux的命令,執行了會報錯說abd命令未找到的錯誤信息輸出,那么這個錯誤信息需要用2>重定向符才能把進程錯誤輸出的內容重定向到指定的文件。
無論進程輸出的信息是正確還是錯誤的信息,都會重定向到指定的文件里,如下例子:
[root@lincoding home]# abc &> file.txt [root@lincoding home]# cat file.txt -bash: abc: command not found [root@lincoding home]# free -m &> file.txt [root@lincoding home]# cat file.txt total used free shared buffers cached Mem: 980 918 62 0 71 547 -/+ buffers/cache: 299 681 Swap: 1983 0 1983
1
2
3
4
5
6
7
8
9
輸入重定向和輸出重定向組合使用
輸入和輸出也是可以組合使用的,那么這個組合主要應用于在Shell腳本當中產生新的配置文件的場景,如下Shell腳本例子:
#!/bin/bash cat > /home/a.sh << EOF echo "hello bash" EOF
1
2
3
4
把cat命令的輸出重定向到/root/a.sh腳本文件,并且用輸入重定向把EOF為腳本結尾。那么通過執行這個腳本,就會產生一個內容為echo "hello bash"文件名為a.sh的腳本文件。
執行結果:
[root@lincoding home]# ./test.sh [root@lincoding home]# ls -l a.sh -rw-r--r--. 1 root root 18 Sep 27 16:41 a.sh [root@lincoding home]# chmod u+x a.sh [root@lincoding home]# cat a.sh echo "hello bash" [root@lincoding home]# ./a.sh hello bash
1
2
3
4
5
6
7
8
小結
以上的內容就是關于輸入和輸出重定向的用法,那么大家要注意輸出重定向包括覆蓋和追加模式,無論是覆蓋還是追加模式,盡量不要用于我們的系統配置文件,那么在應用之前大家要注意對系統文件進行備份。
輸入和輸出重定向,還可以組合使用,一般在Shell腳本當中去產生新的配置文件的時候,會用到它們的組合的方式。
Shell 任務調度
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。