shell中使用管道符需要注意的点

写个监控采集脚本有一处使用了管道符,运行结果出乎意料,特来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会为空

猜你喜欢

转载自www.cnblogs.com/Bccd/p/12679164.html