this post was submitted on 17 Jan 2025
2 points (75.0% liked)

Bash

876 readers
1 users here now

Talk about the Bash Shell and Bash scripting

founded 4 years ago
MODERATORS
 

In the code below we wait for a background process three times. In the first paragraph we get the expected 0 return code from the wait. In the second paragraph the only change is wrapping the wait in a command substitution which instead gives a 255 return code. In the third paragraph the only change is wrapping the wait in a subshell which gives a 127 return code. Why is this?

sleep 1 &
wait $!
echo $?                     # prints "0"

sleep 1 &
a=$(wait $!)                # <---- only difference is cmd substitution
echo $?                      # prints "255"

sleep 1 &
(wait $! &>/dev/null)       # <---- only difference is subshell
echo $?                     # prints "127"

Thanks in advance for your thoughts!

EDIT: updated to include the subshell final example also, which gives a clue

top 2 comments
sorted by: hot top controversial new old
[โ€“] [email protected] 2 points 2 months ago (1 children)

I would assume the cause is that the subshell does not have a previous command to wait on.

[โ€“] [email protected] 1 points 1 month ago

Thanks, that was it! I've updated the post to include a final subshell example where we get the 127 return code we might have expected instead of the 255 from the second paragraph.

There's something different about cmd substitution subshells to regular ones that produces this behaviour (the 255), it's a quirk of BASH.