当前位置: 首页> 教育> 幼教 > shell脚本编程-任务后台运行及状态传递

shell脚本编程-任务后台运行及状态传递

时间:2025/8/26 10:12:19来源:https://blog.csdn.net/yuxuan89814/article/details/139291598 浏览次数:0次

需求:

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+=(元素)

关键字:shell脚本编程-任务后台运行及状态传递

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: