Bash 脚本等待进程并获取返回码

Hug*_*ugo 15 linux bash process array

我正在尝试创建一个脚本,它将启动许多后台命令。对于每个后台命令,我都需要获取返回码。

我一直在尝试以下脚本:

 #!/bin/bash
set -x
pid=()
return=()


for i in 1 2
do
 echo start $i
 ssh mysql "/root/test$i.sh" &
 pid[$i]=$!
done

for i in ${#pid[@]}
do
echo ${pid[$i]}
wait ${pid[$i]}
return[$i]=$?

if [ ${return[$i]} -ne 0 ]
then
  echo mail error
fi

done

echo ${return[1]}
echo ${return[2]}
Run Code Online (Sandbox Code Playgroud)

我的问题是在等待循环期间,如果第二个 pid 在第一个之前完成,我将无法获得返回码。

我知道我可以运行wait pid1 pid2,但是使用此命令我无法获取所有命令的返回码。

任何的想法 ?

Sté*_*las 9

问题更多的是你的

for i in ${#pid[@]}
Run Code Online (Sandbox Code Playgroud)

这是for i in 2.

而是应该是:

for i in 1 2
Run Code Online (Sandbox Code Playgroud)

或者

for ((i = 1; i <= ${#pid[@]}; i++))
Run Code Online (Sandbox Code Playgroud)

wait "$pid" 返回作业的退出代码bash(和POSIX炮弹,但没有zsh),即使在工作时就已经终止wait已启动。


Chr*_*own 7

您可以使用临时目录来执行此操作。

# Create a temporary directory to store the statuses
dir=$(mktemp -d)

# Execute the backgrouded code. Create a file that contains the exit status.
# The filename is the PID of this group's subshell.
for i in 1 2; do
    { ssh mysql "/root/test$i.sh" ; echo "$?" > "$dir/$BASHPID" ; } &
done

# Wait for all jobs to complete
wait

# Get return information for each pid
for file in "$dir"/*; do
    printf 'PID %d returned %d\n' "${file##*/}" "$(<"$file")"
done

# Remove the temporary directory
rm -r "$dir"
Run Code Online (Sandbox Code Playgroud)


小智 5

没有临时文件的通用实现。

#!/usr/bin/env bash

## associative array for job status
declare -A JOBS

## run command in the background
background() {
  eval $1 & JOBS[$!]="$1"
}

## check exit status of each job
## preserve exit status in ${JOBS}
## returns 1 if any job failed
reap() {
  local cmd
  local status=0
  for pid in ${!JOBS[@]}; do
    cmd=${JOBS[${pid}]}
    wait ${pid} ; JOBS[${pid}]=$?
    if [[ ${JOBS[${pid}]} -ne 0 ]]; then
      status=${JOBS[${pid}]}
      echo -e "[${pid}] Exited with status: ${status}\n${cmd}"
    fi
  done
  return ${status}
}

background 'sleep 1 ; false'
background 'sleep 3 ; true'
background 'sleep 2 ; exit 5'
background 'sleep 5 ; true'

reap || echo "Ooops! Some jobs failed"
Run Code Online (Sandbox Code Playgroud)