Shell – What’s the difference between && and ; when forking sleep to background

background-processshellsleep

I have just asked a question about forking a process to sleep in the backgroud.
The notation I came up with myself looks like this:

sleep 10 && echo "hello world" &

This answer to a different question uses a different format.

( sleep 10 ; echo "hello world" ) &

I know that && only allows the second process to start if the first one returns true. Can sleep fail? Is there a situation where I should prefer one over the other?

Best Answer

Sleep can fail if it is terminated during execution:

$ sleep 2
$ echo "$?"
0
$ sleep 2
^C
$ echo "$?"
130

Since sleep is an external executable, it is also conceivable that the fork or exec calls could fail, which would also cause bash to generate an error code >0.

Related Question