快速入門Shell編程(五)輸入輸出重定向

重定向作用

一個進程默認會打開標準輸入、標準輸出、錯誤輸出三個文件描述符。

重定向可以讓我們的程序的標準輸出、錯誤輸出的信息重定向文件裏,那麼這裏還可以將文件的內容代替鍵盤作爲一種標準輸入的方式。


重定向符號

  • 輸入重定向符號"<"

  • 輸出重定向符號">",">>","2>","&>"


輸入重定向功能

01 輸入重定向符號"<"的作用:

會把文件的內容當做參數輸入到進程,如下例子:

[root@omp120 home]# cat file.txt 
hello
[root@omp120 home]# read a < file.txt 
[root@omp120 home]# echo $a
hello

file.txt文件的內容是hello,上述的例子就是把file.txt的內容重定向到a這個變量,並把a變量打印出來。


輸出重定向功能

01 輸出重定向符號">"的作用:

會把文件內容清空,在把輸出內容重定向到指定的文件裏,並且如果文件不存在則創建,如下例子:

[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
02 輸出重定向符號">>"的作用:

會把輸出的內容追加到指定的文件裏,該文件不會被清空,並且如果文件不存在則創建,如下例子:

[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
03 輸出重定向符號"2>"的作用:

是把進程錯誤輸出的內容重定向到指定的文件裏,如下例子:

[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

以上的演示結果可以得知,abc不是Linux的命令,執行了會報錯說abd命令未找到的錯誤信息輸出,那麼這個錯誤信息需要用2>重定向符才能把進程錯誤輸出的內容重定向到指定的文件。

04 輸出重定向符號"&>"的作用:

無論進程輸出的信息是正確還是錯誤的信息,都會重定向到指定的文件裏,如下例子:

[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

輸入重定向和輸出重定向組合使用

輸入和輸出也是可以組合使用的,那麼這個組合主要應用於在Shell腳本當中產生新的配置文件的場景,如下Shell腳本例子:

#!/bin/bash
cat > /home/a.sh << EOF
echo "hello bash"
EOF

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

小結

以上的內容就是關於輸入和輸出重定向的用法,那麼大家要注意輸出重定向包括覆蓋和追加模式,無論是覆蓋還是追加模式,儘量不要用於我們的系統配置文件,那麼在應用之前大家要注意對系統文件進行備份。

輸入和輸出重定向,還可以組合使用,一般在Shell腳本當中去產生新的配置文件的時候,會用到它們的組合的方式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章