shell 仅在运行所有命令后退出脚本[重复]

f5emj3cl  于 2022-12-19  发布在  Shell
关注(0)|答案(1)|浏览(132)
    • 此问题在此处已有答案**:

How to wait in bash for several subprocesses to finish, and return exit code !=0 when any subprocess ends with code !=0?(34个答案)
5天前关闭。
我希望我的shell脚本失败,如果一个特定的命令失败。但是在任何情况下,运行整个脚本。所以我想在命令的结尾使用return 1,我想"捕捉",也许在结尾添加一个条件,如:if return 1; then exit 1。我有点搞不懂它应该是什么样子。

#!/bin/bash

command 1 

# I want THIS command to make the script fail. 
# It runs test and in parallel regex
command 2 &

# bash regex that HAS to run in parallel with command 2
regex='^ID *\| *([0-9]+)'
while ! [[ $(command 3) =~ $regex ]] && jobs -rp | awk 'END{exit(NR==0)}'
do
    sleep 1
done

...

# Final command for creation of a report 
# Script has to run this command also if command 2 fails
command 4
wz3gfoph

wz3gfoph1#

trap是您的朋友,但您必须小心那些后台任务。

$: cat tst
#!/bin/bash
trap 'let err++' ERR
{ trap 'let err++' ERR; sleep 1; false; } & pid=$!
for str in foo bar baz ;do echo $str; done
wait $pid
echo happily done
exit $err

$: ./tst && echo ok || echo no
foo
bar
baz
happily done
no

只是要确保你测试了所有的逻辑。

相关问题