2017-10-21 229 views
1

我有10个指令并行执行:基于bash shell脚本中命令的退出状态的回调?

comdA & comdB & comdC & comdD 

...

有如果这些命令返回0以外的退出状态执行的回调的方式?

如果这是不可能的使用bash。如何PHP?我可以

function exec_with_callback ($comd) { 

    shell_exec($comd); 
    callback(); 

} 

exec_with_callback("comdA"); 
exec_with_callback("comdB"); 
... 
but in parallel? 

如果不是,我可以使用哪种其他语言?

+1

https://stackoverflow.com/questions/9258387/bash-ampersand-operator – chiliNUT

回答

1

可以在循环中执行你的命令,并保存使用$! shell变量,让你最后的后台作业的进程ID process_ids。

n=0 
commands=(comdA comdB comdC comdD) #storing all 10 commands in an array. store the status of each execution in another array 
for cmd in ${commands[@]}; do 
    ${cmd} & 
    pid=$! 
    pidarray[$n]=${pid} 
    ((n+=1)) 
done 

等待所有流程在循环中使用wait <PID>完成。

n=0 
for pid in ${pidarray[@]}; do 
    wait ${pid} 
    exit_status_array[$n]=$? 
    ((n+=1)) 
done 

现在循环遍历exit_status_array和回调对应的命令,如果退出状态比0

n=0 
for s in ${exit_status_array[@]}; do 
    if [[ ${s} -ne 0 ]]; then 
    commands[$n] & #callback 
    fi 
    ((n+=1)) 
done 

其他可以使用这个逻辑和调用等功能无限期如果你想重复这个过程,

0

也许你可以使用这个:

#!/bin/bash 

function check() { 
    $1 >/dev/null 2>&1 
    echo $? 
} 

command=("curl -sSL google.com" "echo 1" 'ping localhost -c 1' 'ls' 'false') 

for ((i=0;i<${#command[@]};i++)); do 
    echo "Command \"${command[$i]}\" returned value $(check "${command[$i]}")" 
    if (($(check "${command[$i]}") != 0)); then second=1; fi 
done 

if ((second == 1)); then 
    echo "I must run second group of commands because something have not worked!" 
    echo 2 
else 
    echo "All is gone without issues! Goodbye $USER!" 
    exit 0 
fi 

检查函数运行命令并返回退出状态,命令进入命令数组,使用for循环可以看到所有运行的命令及其退出状态。如果某人的退出状态不等于零,那么当所有命令与其他命令完成时,变量会帮助我们运行一个if。

输出

[email protected]:~/Scrivania$ bash example 
Command "curl -sSL google.com" returned value 0 
Command "echo 1" returned value 0 
Command "ping localhost -c 1" returned value 0 
Command "ls" returned value 0 
Command "false" returned value 1 
I must run second group of commands because something have not worked! 
2 
[email protected]:~/Scrivania$ bash example 
Command "curl -sSL google.com" returned value 0 
Command "echo 1" returned value 0 
Command "ping localhost -c 1" returned value 0 
Command "ls" returned value 0 
Command "true" returned value 0 
All is gone without issues! Goodbye darby! 
[email protected]:~/Scrivania$ 
0

的实施例准备由线含有一个命令文件myCommands

echo "curl -sSL google.com" > myCommands.txt 
echo "echo 1"    >> myCommands.txt 
echo "ping localhost -c 1" >> myCommands.txt 
echo "ls"     >> myCommands.txt 
echo "false"    >> myCommands.txt 

,然后使用xargs的,并检查的xargs返回代码。

xargs --arg-file myCommands.txt --max-procs 5 -I COMMAND sh -c "COMMAND" 
[ $? -eq 0 ] && echo "All command have sucessfully finish with retrun code 0" && echo "You need check the result" 

如果代码返回等于0 ==>在myCommands文件中的所有命令已经成功,返回代码完成0

--max-procs:运行到在时间MAX-特效过程;默认值为1。如果 MAX-特效是0,xargs的将在同一时间运行多个程序尽可能 。