I have two background jobs with job id 1 and 2. I want to do something when job 1 is done, but I don't want to hang.

Currently what I get is wait 1 && do whatever, but this command it self blocks current shell. I want to let wait itself runs background. I tried wait 1 & && do whateverin zsh but it doesn't work. I get an error : zsh: parse error near '&&'.

Note: it's import that I want to wait in background rather than wait for some background jobs to be done.

  • Erm, ( wait 1 && do whatever ) &? – Ignacio Vazquez-Abrams Jul 16 '18 at 3:04
  • not work. get error: wait: can't manipulate jobs in subshell – youkaichao Jul 16 '18 at 4:45
  • @IgnacioVazquez-Abrams: in my mind, your compound command may be replaced by cmd1 && cmd2 & cmd3? – Fólkvangr Jul 16 '18 at 6:12
  • @游凯超: Does the two tasks in the background have some connection? – Fólkvangr Jul 16 '18 at 6:36
  • @Fólkvangr no, they are simply all background tasks. I just want to do something when job 1 finishes. – youkaichao Jul 16 '18 at 7:37

The syntax error is because both & and && are command separators. & starts the command in the background and immediately runs the next one, while && runs the first command, waits for it to finish, and runs the second command if the first one succeeded.

To background two things that you want to run asynchronous to a third thing, use this pattern:

( first_thing && second_thing ) &

Optionally wait $! after third_thing to finish the first two before continuing.

wait 1 waits for PID 1 to finish, which is unlikely to ever happen while your shell is running. You'll want wait %1, which waits for job spec 1.

  • I change 1 to %1, but still get zsh: parse error near `&&'. what should I do? – youkaichao Jul 16 '18 at 4:46
  • I think this can be a comment rather than an answer. This is not a solution to the question. – youkaichao Jul 16 '18 at 4:48
  • You should try this before you answer. It of course does not work since process id 1 is not your child. – schily Jul 16 '18 at 8:16
  • @schily the pid is not the key point of this question. In practice, I would of course use the actual pid. The key point is how to wait and this answer doesn't talk about it. – youkaichao Jul 16 '18 at 23:39

I think wait is not the answer. according to this , tail is a better solution. I should use ( tail --pid=WHATEVER -f /dev/null && do whatever ) &

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.