简体   繁体   中英

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. 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.

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. Simply try running the python script alone and take note if control returns immediately to the console or not.

You could run the command halt to stop your system:

   #!/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). 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.

Alternatively, you can use command substitution like this:

$(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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