Pregunta

I want to reference a background Bash job in another background Bash job. Is that possible?

For example, say I start a background job:

$ long_running_process &
[1] 12345

Now I want something to happen when that job finishes, so I can use wait:

$ wait %1 && thing_to_happen_after_long_running_process_finishes

However, that will block, and I want my terminal back to do other stuff, but Ctrl+Z does nothing.

Attempting to start this in the background in the first place instead fails:

$ { wait %1 && thing_to_happen_after_long_running_process_finishes; } &
[2] 12346
-bash: line 3: wait: %1: no such job
$ jobs
[1]-  Running     long_running_process &
[2]+  Exit 127    { wait %1 && thing_to_happen_after_long_running process_finishes; }

Is there some way to reference one job using wait in another background job?

I see this behaviour using GNU Bash 4.1.2(1)-release.

¿Fue útil?

Solución

A shell can only wait on its own children. Since backgrounding a job creates a new shell, a wait in that shell can only wait on its own children, not the children of its parent (i.e., the shell from which the background-wait forked). For what you want, you need to plan ahead:

long_running_process && thing_to_happen_after &

There is one alternative:

long_running_process &
LRP_PID=$!

{ while kill -0 $LRP_PID 2> /dev/null; do sleep 1; done; thing_to_happen_after; } &

This would set up a loop that tries to ping your background process once a second. When the process is complete, the kill will fail, and move on to the post-process program. It carries the slight risk that your process would exit and another process would be given the same process ID between checks, in which case the kill would become confused and think your process was still running, when in fact it is the new one. But it's very slight risk, and actually it might be OK if thing_to_happen_after is delayed a little longer until there is no process with ID $LRP_PID.

Otros consejos

try something like this :

  x2=$(long_running_process && thing_to_happen_after_long_running_process_finishes ) &
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top