bash 如何在继续 shell 脚本之前等待任务完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3302891/
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
How to wait for a task to complete before continuing shell script
提问by ma?ek
I have two shell scripts to write that will be executed nightly via cron schedule.
我有两个 shell 脚本要编写,它们将通过 cron 计划每晚执行。
On my production server:
在我的生产服务器上:
mysqldump -ufoo -pbar --opt --routines db > ~/sqldump/{$todays_date}.sqlln -s ~/sqldump/{$todays_date}.sql latest.sql
mysqldump -ufoo -pbar --opt --routines db > ~/sqldump/{$todays_date}.sqlln -s ~/sqldump/{$todays_date}.sql latest.sql
On my development server:
在我的开发服务器上:
scp [email protected]:~/sqldump/latest.sql ~/sqldumpmysql -ufoo -pbar db < latest.sql
scp [email protected]:~/sqldump/latest.sql ~/sqldumpmysql -ufoo -pbar db < latest.sql
I have two questions:
我有两个问题:
- In the production server job, how do i get
$todays_dateto fill in the date? e.g., "2010-07-21" - How do I make step two wait for step 1 to finish in each job?
- 在生产服务器工作中,如何
$todays_date填写日期?例如,“2010-07-21” - 如何让第二步等待每项工作的第一步完成?
回答by R Samuel Klatchko
To get today's date, use date +%F:
要获取今天的日期,请使用date +%F:
command > ~/sqldump/$(date +%F).sql
To read more about the various options you can use with date's +formatting, check out the date man page.
要了解有关可用于日期+格式的各种选项的更多信息,请查看日期手册页。
As for waiting, I assume you mean you don't want to run the command on your dev server until the commands on your prod server are done. The best idea would be to have the dev server start the command using ssh (i.e. ssh user@host "mysqldump ... > ... && ln -s ...).
至于等待,我假设你的意思是你不想在你的开发服务器上运行命令,直到你的生产服务器上的命令完成。最好的办法是让开发服务器使用 ssh(即ssh user@host "mysqldump ... > ... && ln -s ...)启动命令。
If you don't want to do that, the best I can think of is to use a temp file so that the dump file creation is atomic:
如果您不想这样做,我能想到的最好的方法是使用临时文件,以便转储文件的创建是原子的:
mysqldump ... > ~/sqldump/tmp$$ && mv ~/sqldump/tmp$$ ~/sqldump/$(date +%F).sql
Then if you have your dev server request's the dump from today's date, then you can loop until the scp succeeds:
然后,如果您的开发服务器请求是今天日期的转储,那么您可以循环直到 scp 成功:
while ! scp [email protected]:~/sqldump/$(date +%F).sql ~/sqldump; do
# file not present yet, sleep 1 minute and try again
sleep 60
done
mysql -ufoo -pbar db < latest.sql
回答by Darron
Unless you use an "&" at the end of the command for step one, step two will automatically wait for it.
除非您在第一步的命令末尾使用“&”,否则第二步将自动等待它。

