operating_system:nix_bash_i_o_redirection

[*nix] Bash I/O Redirection

0x00 前言

在UNIX系統中我們使用shell、在shell中下指令,也會寫些shell script,而這之中常常會用到pipe與redirection

本篇記錄一些bash shell中會使用到的redirection表示法


0x01 File Descriptors

UNIX中的file descriptors是抽象化的指標概念,用於存取檔案或其他input/output resource,像是pipe或是network connection

file descriptor是非負整數,對於每個UNIX process(daemon部分例外),我們預期會有三個基本的file descriptor

分別是

Integer Value Name <unistd.h> symbolic constant <stdio.h> file stream
0 Standard input STDIN_FILENO stdin
1 Standard output STDOUT_FILENO stdout
2 Standard error STDERR_FILENO stderr

0x02 I/O Description

Symbol description
>filename or : >filename 若該檔案不存在就建立一個zero length的檔案(同touch),若檔案存在則將檔案截斷(truncates)為zero length,將output重導到file。部分shell僅支援有:的寫法
>>filename 若檔案不存在會自動建立,若檔案存在則會以附加在檔案尾端的方式將output重導到file
1>filename 將stdout以覆蓋寫入方式重導到file
1>>filename 將stdout以附加寫入方式重導到file
2>filename 將stderr以覆蓋寫入方式重導到file
2>>filename 將stderr以附加寫入方式重導到file
&>filename 將stdout&stderr以覆蓋寫入方式重導到file
M>N M是file descriptor,預設是1(stdout),N是file name,file descriptor M會被重導到file N
M>&N M和N皆為file descriptor,將file descriptor M重導到file descriptor N,依次輸出
>>filename 2>&1 上句用法的範例,將stderr重導到stderr,stdout和stderr都會被附加寫入file
i>&j 將file descriptor i重導到file descriptor j
>&j 上句用法的簡寫,i不只定的話預設為1
0<filename or <filename 接受file為stdin
<< “string” 像使用cat等指令程式會等待stdin,最後收到ctrl-D後結束stdin,此方式可透過使用自訂string結束stdin像是eof
[j]<>filename 打開檔案來讀取和寫入,並把file descriptor j指派給這個file,若檔案不存在會自動建立,若file descriptor沒指定則預設用0(stdin)
| 用於串聯指令
n<&- 關閉input file descriptor n
0<&- or <&- 關閉stdin
n>&- 關閉output file descriptor n
1>&- or >&- 關閉stdout

0x03 參考資料

operating_system/nix_bash_i_o_redirection.txt · 上一次變更: 127.0.0.1