在Shell脚本中,可以使用并行运行子shell并收集退出码的方法有以下几种:
&
符号将子shell放在后台运行,并使用wait
命令等待所有子shell执行完毕。在子shell运行完成后,可以使用$?
获取每个子shell的退出码。#!/bin/bash
# 启动多个子shell并行运行
command1 &
pid1=$!
command2 &
pid2=$!
command3 &
pid3=$!
# 等待子shell运行完成
wait $pid1
exit_code1=$?
wait $pid2
exit_code2=$?
wait $pid3
exit_code3=$?
echo "Command 1 exit code: $exit_code1"
echo "Command 2 exit code: $exit_code2"
echo "Command 3 exit code: $exit_code3"
&
符号将子shell放在后台运行,并使用$!
获取每个子shell的进程ID。然后可以使用wait
命令等待所有子shell执行完毕,并使用$?
获取每个子shell的退出码。#!/bin/bash
# 启动多个子shell并行运行
command1 &
pid1=$!
command2 &
pid2=$!
command3 &
pid3=$!
# 等待所有子shell运行完成
wait $pid1
exit_code1=$?
wait $pid2
exit_code2=$?
wait $pid3
exit_code3=$?
echo "Command 1 exit code: $exit_code1"
echo "Command 2 exit code: $exit_code2"
echo "Command 3 exit code: $exit_code3"
&
符号将子shell放在后台运行,并使用数组来保存每个子shell的进程ID。然后可以使用循环等待每个子shell执行完毕,并使用$?
获取每个子shell的退出码。#!/bin/bash
# 启动多个子shell并行运行,并保存进程ID到数组中
pids=()
command1 &
pids+=($!)
command2 &
pids+=($!)
command3 &
pids+=($!)
# 等待所有子shell运行完成,并收集每个子shell的退出码
exit_codes=()
for pid in "${pids[@]}"; do
wait $pid
exit_codes+=($?)
done
# 输出每个子shell的退出码
for i in "${!exit_codes[@]}"; do
echo "Command $((i+1)) exit code: ${exit_codes[i]}"
done
以上是三种常见的并行运行子shell并收集退出码的方法,可以根据具体需求选择合适的方法。