LINUX CORE · 82
Shell / Pipes / Redirect / Exit Code:Process 之間怎麼傳資料
Linux shell 的威力不只來自單一 command,而是把很多小 process 串成 pipeline。要看懂 shell debugging,就要分 stdout、stderr、stdin、exit code,以及 shell 自己的 parsing/redirect 行為。
Learning outcomes
- 能區分 stdin/stdout/stderr。
- 能使用 pipe 與 redirect。
- 能解釋 exit status。
- 能避免因 quoting/globbing 造成 command scope 錯誤。
1. Standard streams
stdin → process
stdout → normal output
stderr → diagnostics/errorsstdout/stderr 是兩條不同 streams,automation 可以分別處理。
2. Pipe
ps aux |
grep node |
head前一個 process 的 stdout 成為下一個 process 的 stdin。這不是「把 command 黏在一起」而是資料流。
3. Redirect
command > out.txt
command 2> err.txt
command >> out.txt> 覆寫 stdout;2> redirect stderr;>> append。
4. Exit status
curl -f https://example.com
echo $?慣例上 0 表示 success,非 0 表示某種 failure。CI/shell script 常依 exit code 決定是否繼續。
5. Quoting / globbing
rm *.log
echo "$HOME"
echo '$HOME'Shell 會先處理 wildcard、variable expansion、quoting,再啟動 process。很多「command 行為怪」其實 root cause 在 shell parsing。
Project checkpoint:Server Workspace v2
建立 log pipeline:從 app.log 過濾 ERROR、取最後 20 行、輸出到 incident.txt,並保存 command exit status。
grep "ERROR" app.log |
tail -n 20 > incident.txt
echo $?Debug evidence:pipeline 沒資料
逐段拆開跑:第一個 command 有沒有 stdout?grep pattern 是否 match?redirect 是否把 output 寫到別處?不要直接把整條 pipeline 當黑盒。
Knowledge check
- stderr 和 stdout 為何分開?
- Pipe 傳的是前一步哪個 stream?
- exit code 0 的慣例?
- 把一條三段 pipeline 拆開驗證每一步。