Bash Shell – Adding ‘&& prog2’ to an Already Running Prog1

bashexitprocessshell

Most shells provide functions like && and ; to chain the execution of commands in certain ways. But what if a command is already running, can I still somehow add another command to be executed depending on the result of the first one?

Say I ran

$ /bin/myprog
some output...

but I really wanted /bin/myprog && /usr/bin/mycleanup. I can't kill myprog and restart everything because too much time would be lost. I can Ctrl+Z it and fg/bg if necessary. Does this allow me to chain in another command?

I'm mostly interested in bash, but answers for all common shells are welcome!

Best Answer

You should be able to do this in the same shell you're in with the wait command:

$ sleep 30 &
[1] 17440

$ wait 17440 && echo hi

...30 seconds later...
[1]+  Done                    sleep 30
hi

excerpt from Bash man page

wait [n ...]
     Wait for each specified process and return its termination status. Each n 
     may be a process ID or a job specification; if a job spec is given,  all 
     processes  in that job's pipeline are waited for.  If n is not given, all 
     currently active child processes are waited for, and the return status is 
     zero.  If n specifies a non-existent process or job, the return status is 
     127.  Otherwise, the return status is the exit status of the last process 
     or job waited for.