Bash Script 调用另一个 bash 脚本并等待它完成后再继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2270081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash Script Calls another bash script and waits for it to complete before proceeding
提问by BassKozz
I have 1 bash script that runs another bash script, however the first bashscript isn't waiting for the second one to complete before proceeding, how can I force it to wait?
我有 1 个运行另一个 bash 脚本的 bash 脚本,但是第一个 bash 脚本在继续之前不会等待第二个脚本完成,我该如何强制它等待?
For example:
例如:
#!/bin/bash
# first.sh
#call to secondary script
sh second.sh
echo "second.sh has completed"
echo "continuing with the rest of first.sh..."
The way it is now, it will run second.sh, and continue on, without waiting for second.sh to complete.
按照现在的方式,它将运行 second.sh,并继续运行,无需等待 second.sh 完成。
采纳答案by Ignacio Vazquez-Abrams
Normally it does; something else is happening. Are you sure that the other script isn't running something in the background instead? You can try using wait
regardless.
通常是这样;其他事情正在发生。您确定另一个脚本没有在后台运行某些东西吗?wait
无论如何都可以尝试使用。
回答by setevoy
AS I use scheme like this in few scripts - just calling second scripts in the same shell-copy using source
.
因为我在几个脚本中使用这样的方案 - 只是使用source
.
In script-1
:
在script-1
:
source script2.sh
or:
或者:
. script2.sh
So - no one command in script-1
will not be proceeded till script2.sh
will end all it's tasks.
所以 - 在结束所有任务script-1
之前,script2.sh
不会执行任何命令。
Little example.
小例子。
First script:
第一个脚本:
$ cat script-1.sh
#!/bin/bash
echo "I'm sccript $ cat script-2.sh
#bin/bash
echo "I'm script-2. Running wait operation..."
sleep 2
echo "I'm ended my task."
."
echo "Runnig script-2..."
source script-2.sh
echo "script-2.sh finished!"
Second script:
第二个脚本:
$ ./script-1.sh
I'm sccript ./script-1.sh.
Runnig script-2...
I'm script-2. Running wait operation...
I'm ended my task.
script-2.sh finished!
How it works:
这个怎么运作:
##代码##回答by Debugger
You can simply add the command wait
after you execute the second script, it will wait for all process that you launch from your principal script
您可以wait
在执行第二个脚本后简单地添加命令,它将等待您从主体脚本启动的所有进程
You can even recuperate the PID of your second script using the command echo $!
directly after you call the second script, and then pass this PID as an argument to the wait
command
您甚至echo $!
可以在调用第二个脚本后直接使用命令恢复第二个脚本的 PID ,然后将此 PID 作为参数传递给wait
命令
回答by ghostdog74
try using bash second.sh
and check your second.sh and make sure you don't have programs that run in the background
尝试使用bash second.sh
并检查您的 second.sh 并确保您没有在后台运行的程序
回答by upteryx
Another way to do it $(second.sh)
另一种方法 $(second.sh)