基于bash shell脚本中命令的退出状态的回调?

时间:2017-10-21 13:33:24

标签: php bash shell

我有10个并行执行的命令:

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?

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

3 个答案:

答案 0 :(得分:1)

您可以循环执行命令并使用$! shell变量保存process_ids,该变量为您提供上一个后台作业的进程ID。

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

如果你想通过使用这个逻辑并调用函数等,你可以无限期地重复这个过程。

答案 1 :(得分: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。

输出示例

darby@Debian:~/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
darby@Debian:~/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!
darby@Debian:~/Scrivania$

答案 2 :(得分: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 ==&gt; myCommands文件中的所有命令都已成功完成,返回码为0

--max-procs:一次运行max-procs进程;默认值为1.如果               max-procs为0,xargs将运行尽可能多的进程               一次。