iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 6
1
自我挑戰組

Linux學習系列 第 6

Linux資料流重導向指令

學習網址:
https://www.guru99.com/linux-redirection.html

Redirection就是當執行指令,可以改變輸入、輸出裝置
預設輸入是鍵盤,預設輸出是螢幕

大於(輸出)+檔案名稱
如果文字檔本來就有文字,用>會覆蓋原本的文字
如果要接著寫,要用>>
https://ithelp.ithome.com.tw/upload/images/20181019/20111994MElNu4fNfj.png

接著講到mail指令,對mail的基礎觀念不夠,加上自己測試mail時,郵件送不到,就先跳過

接著講到File Descriptors
File Descriptors (FD)

Every File has an associated number called File Descriptor (FD).

任何檔案都有一個數字,叫File Descriptor (FD)

Your screen also has a File Descriptor. When a program is executed the output is sent to File Descriptor of the screen, and you see program output on your monitor. If the output is sent to File Descriptor of the printer, the program output would have been printed.

螢幕也有File Descriptor.,當程式正在執行輸出,程式會得到螢幕的File Descriptor,這樣你就看的到螢幕輸出的東西,如果得到的是印表機的File Descriptor,那就會變印表機輸出的東西

Whenever you execute a program/command at the terminal, 3 files are always open, viz., standard input, standard output, standard error.

執行程式時,有3個檔案一定會開啟:輸入、輸出、錯誤

網址的這張圖,顯示:
File Descriptor0 輸入(STDIN)
File Descriptor1 輸出(STDOUT)
File Descriptor2 錯誤(STDERR)
https://www.guru99.com/images/Streams.png

Why Error Redirection?

Error re-direction is one of the very popular features of Unix/Linux.

Frequent UNIX users will reckon that many commands give you massive amounts of errors.

For instance, while searching for files, one typically gets permission denied errors. These errors usually do not help the person searching for a particular file.
While executing shell scripts, you often do NOT want error messages cluttering up the normal program output.

錯誤常re-direction,因為像是searching for files,可能會有gets permission denied errors,這種錯誤沒有幫助searching for files,所以不必要顯示在終端機;或者不希望正常的輸出和錯誤混著一起顯示。

範例一:
找不到指令這個錯誤,會顯示在文件檔,而不是直接顯示在terminal
https://ithelp.ithome.com.tw/upload/images/20181019/20111994Z9UgOByVfe.png

範例二:
在Documents找123檔案,會有錯誤顯示沒這個檔案(STDERR),並且顯示Documents資料夾其他的檔案(STDOUT),接著把STDOUT輸出到dirlist,可是還是沒辦法消除STDERR
https://ithelp.ithome.com.tw/upload/images/20181019/20111994OiDcCi13fe.png

2>&1 means that STDERR redirects to the target of STDOUT (which is the file dirlist)
We are redirecting error output to standard output which in turn is being re-directed to file dirlist. Hence, both the output is written to file dirlist
這邊解釋了2>&1的意思,這樣就可以把STDERR也輸出到dirlist
https://ithelp.ithome.com.tw/upload/images/20181019/20111994cTTFYmDwOo.png

網址:
http://linux.vbird.org/linux_basic/0320bash.php#redirect
這邊有詳細的內容
Note:
1知道錯誤訊息會發生,所以要將錯誤訊息忽略掉而不顯示或儲存呢? /dev/null 可以吃掉任何導向這個裝置的資訊喔!
2有2>&1來將2>轉到1>,那就會有1>&2 來將1>轉到2>


上一篇
Linux檔案權限指令
下一篇
Linux輸入多重指令
系列文
Linux學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言