How to be notified when a script's background job completes?

我的梦境 提交于 2019-12-04 20:48:48

if you run it as source file . then it can notify. e.g.

cat foo.sh

#!/bin/bash
set -mb  # enable job control and notification
sleep 5  &

. foo.sh
[1]+  Done                    sleep 5

The job control of your shell only affects processes controlled by your terminal, that is tasks started directly from the shell.

When the parent process (your script) dies, the init process automatically becomes the parent of the child process (your sleep command), effectively killing all output. Try this example:

[jkramer/sgi5k:~]# cat foo.sh
#!/bin/bash

sleep 20 &
echo $!
[jkramer/sgi5k:~]# bash foo.sh 
19638
[jkramer/sgi5k:~]# ps -ef | grep 19638
jkramer  19638     1  0 23:08 pts/3    00:00:00 sleep 20
jkramer  19643 19500  0 23:08 pts/3    00:00:00 grep 19638

As you can see, the parent process of sleep after the script terminates is 1, the init process. If you need to get notified about the termination of your child process, you can save the content of the $! variable (PID of the last created process) in a file or somewhere and use the `wait´ command to wait for its termination.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!