等待所有进程结束以执行Bash中的下一行

时间:2016-10-05 17:26:38

标签: bash

在我正在编写的脚本中,我创建了许多后台进程,试图在多个设备上并行运行我的脚本。这个功能有效,但看起来我无法控制它。简单的wait命令无法获得我需要的结果。

简要代码:

#!/bin/bash

echo ""

date

echo ""
echo "Displaying devices to be configured:"
./adb devices | sed "1d ; $ d"
echo ""
echo "###########################"
echo "#                         #"
echo "# Starting configuration! #"
echo "#                         #"
echo "###########################"
echo ""

# All commands ran through this function
DeviceConfig () {
  ...
  # Large list of commands
  ...
}

# This is the loop that spawns all the processes. Note the ampersand I'm using.
for usb in $(./adb devices -l | awk '/ device usb:/{print $3}'); do ( DeviceConfig & ) ; done

echo ""
echo "###########################"
echo "#                         #"
echo "# Configuration complete! #"
echo "#                         #"
echo "###########################"

虽然这会成功并行运行我的所有命令,但我的输出并不是预期的。

实际输出:

Wed Oct  5 13:11:26 EDT 2016

Displaying devices to be configured:
3100c2759da2a200    device
3100c2ddbbafa200    device

###########################
#                         #
# Starting configuration! #
#                         #
###########################


###########################
#                         #
# Configuration complete! #
#                         #
###########################

Starting: Intent { cmp=com.android.settings/.Settings }
Warning: Activity not started, its current task has been brought to the front
Starting: Intent { cmp=com.android.settings/.Settings }
Warning: Activity not started, its current task has been brought to the front
...

...意味着脚本输出更多。)

在循环中放置wait并不能解决问题。在循环之后放置wait并不能解决问题。如何编写此循环,以便在Starting configuration!Configuration complete!输出之间进行配置?

1 个答案:

答案 0 :(得分:1)

您可以要求wait等待多个进程,例如:

pids=()

for usb in $(./adb devices -l | awk '/ device usb:/{print $3}'); do DeviceConfig & pids+=($!); done

wait "${pids[@]}"