简体   繁体   English

Shell 运行任务并在任务完成后关闭的脚本

[英]Shell script to run task and shutdown after task is done

I want to run a shell script that runs a python program and shutdowns after the program is done.我想运行一个 shell 脚本,该脚本运行一个 python 程序并在程序完成后关闭。 Here is what I wrote这是我写的

#!/bin/bash
python program
sudo shutdown -h now

This just shutdowns the system without waiting for the program to complete.这只是关闭系统而不等待程序完成。 Is there a different command to use that waits for the program to complete?是否有其他等待程序完成的命令可供使用?

What you have in your example should actually only shutdown once the python command has completed, unless the python program forks or backgrounds early. 您的示例中的内容实际上应该只在python命令完成后关闭,除非python程序早期分叉或背景。

Another way to run it would be to make the shutdown conditional upon the success of the first command 运行它的另一种方法是在第一个命令成功时使关闭成为条件

python command && sudo shutdown -h now

Of course this still will not help you if the python program does anything like forking or daemonizing. 当然,如果python程序执行任何类似forking或daemonizing的操作,这仍然无法帮助你。 Simply try running the python script alone and take note if control returns immediately to the console or not. 只需尝试单独运行python脚本,并注意控件是否立即返回控制台。

You could run the command halt to stop your system: 您可以运行命令halt来停止系统:

   #!/bin/sh
   python program
   sudo halt

The python program is running first, and halt would run after its completion (you might test the exit code of your python program). python program首先运行,并在完成后halt运行(您可能会测试python程序的退出代码)。 If it does not behave like expected, try to understand why. 如果它的行为不符合预期,请尝试理解原因。 You could add a logger command before the halt to write something in the system logs. 您可以在halt之前添加logger命令以在系统日志中写入内容。

Alternatively, you can use command substitution like this:或者,您可以像这样使用command substitution

$(command to run your program)

The script waits until the wrapped command finishes before moving onto the next one!脚本会等到包装的命令完成,然后再转到下一个命令!

#!/bin/sh
$(python program.py)
sudo shutdown -P 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM