首页 > 解决方案 > 问题无法在 bash 脚本中执行所有 bash 脚本

问题描述

我有以下 bash 脚本,它并行运行两个进程(内部有两个 bash 脚本),我需要两个 bash 脚本,两个脚本在两个都完成后并行运行我需要总时间执行。但问题是第一个 bash 脚本 ./cloud.sh 没有运行,但是当我单独运行它时,它运行成功,并且我正在运行具有 sudo 权限的主测试 bash 脚本。

测试

#!/bin/bash
start=$(date +%s%3N)
./cloud.sh &
./client.sh &
end=$(date +%s%3N)
echo "Time: $((duration=end-start))ms."

客户端.sh

#!/bin/bash
sudo docker build -t testing .'

Cloud.sh

#!/bin/bash
start=$(date +%s%3N)
ssh kmaster@192.168.101.238 'docker build -t testing .'
end=$(date +%s%3N)
echo "cloud: $((duration=end-start)) ms"

标签: bashshellunixmultiprocess

解决方案


后台进程将无法从您那里获得键盘输入。一旦它尝试这样做,它就会收到一个SIGTTIN停止它的信号(直到它被带回前台)。

我怀疑你的一个或两个脚本要求你输入一些东西,通常是密码。

Solution 1: configure sudo and ssh in order to make them password-less. With ssh this is easy (ssh key), with sudo this is a security risk. If docker build needs you to enter something, you are doomed.

Solution 2: make only the ssh script (Cloud.sh) password-less and keep the sudo script (Client.sh) in foreground. Here again, if the remote docker build needs you to enter something, this won't work.

How to wait for your background processes? Just use the wait builtin (help wait).

An example with solution 2:

#!/bin/bash
start=$(date +%s%3N)
./cloud.sh &
./client.sh
wait
end=$(date +%s%3N)
echo "Time: $((duration=end-start))ms."

推荐阅读