On a regular basis I forget to add && shutdown -h now
to a long-running process. Is there any way to add a shutdown -h now
command after the first command was invoked? It is not intended to interrupt the ongoing process. Maybe it is possible to watch the PID?
5 Answers
There's no need to repeatedly run ps to list all processes and grep through the output. Background the process with ctrl-Z, then run
bg %1 ; wait %1 ; shutdown -h now
If you have other background jobs running, then you will be given a different jobspec instead of [1] when you ctrl-z. If so, use that instead.
I do this all the time.
- Start the process.
- Realize that I forgot to do my
&&
command. - Hit Ctrl+Z to suspend the process and return to the shell.
- Run
fg && shutdown -h now
to:- Foreground and resume the process you just suspended.
- Then, after it finishes, it'll run what you wanted to run.
Alternatively, you can poll as suggested in other answers like this:
while ps -p $PID ; do sleep 5 ; done ; shutdown -h now
-
-
-
-
@WalkingWiki, oh weird, you are right. I swear I tested this back in 2012 and it completed right away.– psusiJun 22, 2018 at 22:42
You could do something like this, which will check whether the process is running every 5 seconds and take appropriate action:
while true; do
if ps -ef | grep -q '[l]ong-running-process'; then
sleep 5
else
sudo poweroff
fi
done
Note the square brackets in the grep
expression. This is to ensure that the grep
process doesn't get matched if it ends up in the ps
list. Surrounding any single character with square brackets is sufficient.
-
-
-
-
You can also use kill -0 (pid) to check for existence of a process without killing it.– fluffyJan 30, 2012 at 6:15
If You know the pid you can run this:
while ps -p $PID; sleep 5; done; shutdown -h now
To run without echo from ps do this:
while ps -p $PID >/dev/null; sleep 5; done; shutdown -h now
And finally to run it in the background without any output:
(while ps -p $PID >/dev/null; sleep 5; done; shutdown -h now ) &
Scott's solution is a good one but this removes the need to grep
over and over if you already know the pid. And it's a lot quicker to type in. :p
Make a shell script to run both processes:
MyShellScript.txt:
#!/bin/sh
MyProcessIdLikeToStart -o options && shutdown -h now
After saving this in the directory where you start the given process, do a:
chmod +x MyShellScript.txt
Then when you want to run the command just type ./MyShellScript.txt
and it'll do both for you.
&&
will only run if the previous command was successful. If you want it to run even if the command fails use;
instead.