3

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.

3
  • Erm, ( wait 1 && do whatever ) &? Commented Jul 16, 2018 at 3:04
  • not work. get error: wait: can't manipulate jobs in subshell
    – youkaichao
    Commented Jul 16, 2018 at 4:45
  • @Fólkvangr no, they are simply all background tasks. I just want to do something when job 1 finishes.
    – youkaichao
    Commented Jul 16, 2018 at 7:37

2 Answers 2

6

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 ) &
third_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.

4
  • I change 1 to %1, but still get zsh: parse error near `&&'. what should I do?
    – youkaichao
    Commented Jul 16, 2018 at 4:46
  • I think this can be a comment rather than an answer. This is not a solution to the question.
    – youkaichao
    Commented Jul 16, 2018 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
    Commented Jul 16, 2018 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
    Commented Jul 16, 2018 at 23:39
0

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 ) &

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .