寫個監控采集腳本有一處使用了管道符,運行結果出乎意料,特來mark下
結論:管道符和括號會fork出一個子進程,如果在子進程的工作區間內調用exit則退出的只是當前的子進程,不會退出主進程
測試管道符
cat test.sh
#!/bin/bash function work_pipeline(){ seq 3 |while read line; do echo $line if (($line >2));then echo "I'm going to exit" exit fi done } function work_quote(){ for line in $(seq 3) ; do echo $line if (($line >2));then echo "I'm going to exit" exit fi done } function main(){ for i in $(seq 2);do work_pipeline done } main
運行結果
工作函數work_pipeline 在mian函數中被調用了兩次,每次工作函數在遇到2后都會執行exit,但是exit退出的是子進程
sh test.sh 1 2 3 I'm going to exit 1 2 3 I'm going to exit
如果想達到退出主進程的功能需要使用work_quote函數
# 將main函數改寫成 function main(){ for i in $(seq 2);do work_quote done }
# 運行結果
1
2
3
I'm going to exit
測試括號
和管道符一樣會創建子進程,exit退出的只是子進程
# 將main函數改寫成 function main(){ for i in $(seq 2);do (work_quote) done } # 運行結果 1 2 3 I'm going to exit
1
2
3 I'm going to exit
補充一個錯誤使用重定向的案例
ll >t.txt &>/dev/null # t.txt會為空