Bash Shell – Combine Semicolon and Ampersand

bashshell

[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?

Best Answer

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: $!
Related Question