4
[root@localhost tmppcm]# ls ; echo exit code was: $? & echo pid is: $!
test.txt
..
....
.....
......
lastfile.txt
[1] 1265
pid is: 1265
exit code was: 0

In above it is as it runs ls to begin with, and then ends by running the echo's in 'parallel'.

Not quite what I want. I'd like that the sequence ls and echo exit code was: $? to be performed in the background, and echo process id in 'parallel'.

A solution could be to use || instead of ; between ls and echo exit code was:

[root@localhost tmppcm]# ls || echo exit code was: $? & echo pid is: $!
[1] 1271
pid is: 1271
test.txt
..
....
.....
......
lastfile.txt
exit code was: 0

Is there a more clever way to do this with the A ; B & C combination that I'm missing?

  • 1
    since you're using wait it might work for both jobspecs and pids, but there's a chance that command would only work from the prompt, and not within a script. See my question on SO about the difference between testing for a job to finish vs. a process to finsih--they are not identical – Eric Renouf Nov 24 '15 at 21:46
6

In this case you want to use command groups. Since you want some to run in the background we'll use the () variety so they get their own subshell. You can group the commands with the parens, and then put that group (and its subshell) in the background like:

( A; B ) & C

or in this specific example:

(ls ; echo exit code was: $?) & echo pid is: $!
  • 1
    @hyprfrcb the & should be on the same line as the end of the group that is being put in the background. The contents of the subshell can be on separate lines, as can the commands to run after starting the group in the background. That is, A and B can be on separate lines above, and C can be on the line after the & – Eric Renouf Nov 29 '17 at 15:04

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.