问题描述
我正在用bash编写脚本,该脚本在内部调用了两个bash脚本.第一个脚本包含在后台运行的不同测试,第二个脚本打印第一个脚本的结果.
I am writing a script in bash, which is calling two bash scripts internally. Where first script includes different tests which runs in background and second script print results of first script.
当我一个接一个地运行这两个脚本时,有时,第二个脚本会在第一个脚本结束之前执行,这会打印错误的结果.
When I run these two scripts one after other, sometimes, second script get executed before first script ends Which prints wrong results.
我正在使用source命令运行两个脚本.有更好的建议吗?
I am running both scripts with source command. Any better suggestions?
source ../../st_new.sh -basedir $STRESS_PATH -instances $INSTANCES
source ../../results.sh
推荐答案
Shell脚本,无论如何执行,都必须先执行一个命令.因此,您的代码将在st_new.sh
的最后一条命令完成后执行results.sh
.
Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh
after the last command of st_new.sh
has finished.
现在有一个特殊的命令可以将其弄乱:&
Now there is a special command which messes this up: &
cmd &
表示:启动一个新的后台进程并在其中执行cmd
.启动后台进程后,立即继续执行脚本中的下一个命令."
means: "Start a new background process and execute cmd
in it. After starting the background process, immediately continue with the next command in the script."
这意味着&
不会等待cmd
正常工作.我的猜测是st_new.sh
包含这样的命令.如果是这种情况,那么您需要修改脚本:
That means &
doesn't wait for cmd
to do it's work. My guess is that st_new.sh
contains such a command. If that is the case, then you need to modify the script:
cmd &
BACK_PID=$!
这会将新后台进程的进程ID(PID)放入变量BACK_PID
中.然后,您可以等待其结束:
This puts the process ID (PID) of the new background process in the variable BACK_PID
. You can then wait for it to end:
while kill -0 $BACK_PID ; do
echo "Process is still active..."
sleep 1
# You can add a timeout here if you want
done
或者,如果您不想仅进行任何特殊处理/输出
or, if you don't want any special handling/output simply
wait $BACK_PID
请注意,即使您省略了&
,某些程序在运行时也会自动启动后台进程.查看文档,他们通常可以选择将其PID写入文件,或者您可以使用选项在前台运行它们,然后使用Shell的&
命令获取PID.
Note that some programs automatically start a background process when you run them, even if you omit the &
. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's &
command instead to get the PID.
这篇关于如何等待第一个命令完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!