需求:
shell脚本A 通过for循环多次调用B脚本中的方法,参数不同。调用方式是后台运行,即调用函数后面加入&。如何通过B方法是否成功执行,控制A脚本的返回exit 1还是exit 0
test_A.sh
#! /bin/bash
source ./test_B.sh
echo "this is the test_A.sh-start"
pids=()
for i in {1..5};domyfunc $i &pids+=($!)
donefor pid in "${pids[@]}";dowait $pid
if [ $? -ne 0 ];thenecho "at leat one task failed,Existing with status"exit 1
fi
donefor j in {1..100};doecho "test_b end $j"
doneecho "All task successed.Eisting with status 0"
exit 0
test_B.sh
#! /bin/bash
echo "this is the test_B-start"
myfunc(){
echo "this is my func in test B: ${1}"
if [ "${1}" -eq 5 ];thenecho "this is 5!!"exit 1
fi
}
echo "this is the test_B-end"
运行test_A.sh
[sss@git2 run_backend]$ ./test_A.sh
this is the test_B-start
this is the test_B-end
this is the test_A.sh-start
this is my func in test B: 1
this is my func in test B: 2
this is my func in test B: 3
this is my func in test B: 4
this is my func in test B: 5
this is 5!!
at leat one task failed,Existing with status
结果说明
1,source 加载shell文件,是直接运行的。所以才会 打印
this is the test_B-start
this is the test_B-end
2,source加载的文件中的函数变量,是可以直接使用的。所以A中才可以直接使用myfunc
3,使用&可以直接使函数后台运行。 实现并发执行效果。使用 wait 进程号 功能阻塞进程至执行完。进程号获取通过 $!
4, shell中数组使用
pids=()
pid+=(元素)