歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell文件描述符及重定向

Shell文件描述符及重定向

日期:2017/3/1 9:17:48   编辑:SHELL編程

文件描述符是與文件輸入、輸出相關聯的整數。它用來跟蹤已經打開的文件。最常見的文件描述符是stdin、stdout、stderr。我們甚至可以將某個文件描述的內容重定向到另一個文件描述符中。文件描述符0,1,2是系統預留的:

0----stdin(標准輸入)  1----stdout(標准輸出)  2----stderr(標准錯誤)

實例

(一)、將輸出的文本重定向到一個文件中:

[root@localhost shell]# echo "this is a example test"> temp.txt

You have new mail in /var/spool/mail/root

[root@localhost shell]# cat temp

cat: temp: 沒有那個文件或目錄

[root@localhost shell]# cat temp.txt

this is a example test

[root@localhost shell]# echo this is a example test> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

[root@localhost shell]# echo 'this is a example test'> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

(二)、將文本追加到目標文件

[root@localhost shell]# echo 'this is a example test'>> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

this is a example test

[root@localhost shell]# echo this is a example test>> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

this is a example test

this is a example test

(三)、cat 文件名 :查看文件的內容

(四)、標准錯誤的重定向,當命令輸出錯誤信息時,stderr信息就會被打印出來

[root@localhost shell]# ls +

ls: 無法訪問 +: 沒有那個文件或目錄

[root@localhost shell]# echo $?

2

[root@localhost shell]# ls + > out.txt

ls: 無法訪問 +: 沒有那個文件或目錄

[root@localhost shell]# ls + 2> out.txt

[root@localhost shell]# cat out.txt

ls: 無法訪問 +: 沒有那個文件或目錄


第一次的ls + 中的+是非法參數,因此命令將執行失敗;

echo $? 能輸出上個命令執行後狀態;

第三句的ls + >out.txt將執行失敗的信息輸出到了屏幕,並不是文件中,最後一句加上文件描述符才輸出到了文件中,然後可以查看到文件的內容;

(五)、自定義文件描述符

創建文件描述符進行文件讀取;


root@localhost shell]# echo this is s test > input.txt

[root@localhost shell]# exec 3< input.txt

[root@localhost shell]# cat &3

[1] 8171

bash: 3: command not found

[root@localhost shell]# cat 3

cat: 3: 沒有那個文件或目錄

[1]+ Stopped cat

[root@localhost shell]# cat <&3

this is s test

Linux Shell腳本 多線程 http://www.linuxidc.com/Linux/2015-10/123993.htm

cat命令利用Linux重定向合並文件 http://www.linuxidc.com/Linux/2015-01/112122.htm

Shell編程淺析 http://www.linuxidc.com/Linux/2014-08/105379.htm

Linux Shell參數替換 http://www.linuxidc.com/Linux/2013-06/85356.htm

Shell for參數 http://www.linuxidc.com/Linux/2013-07/87335.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、轉義字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved