8

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?

Baarn
  • 882

3 Answers3

12

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.

Chris Down
  • 125,559
  • 25
  • 270
  • 266
5

a; b always runs the second command after the first, whereas a && b runs the second command only if the first is successful, i.e. only if the first command returns the status 0.

sleep always returns the status 0, except when it's killed by a signal, in which case the status is 128 + signal number. (The status can also be 126 or 127 if the sleep command doesn't exist or the program is unable to start due to a lack of resources, but you're highly unlikely to encounter these cases.)

Thus you should use ; or && depending on what you want to happen if the sleep is interrupted:

  • sleep 10; echo hello prints the message after 10 seconds (less if sleep is killed by a signal);
  • sleep 10 && echo hello prints the message after 10 seconds, but prints nothing if sleep is killed by a signal.
3

You should assume that any command can fail for various reasons even if having sleep fail is indeed very unlikely.

( sleep 10 ; echo "hello world" ) &

means background sleep and execute echo after sleeping process but if sleep fails echo will run anyway see complete explanation

sleep 10 && echo "hello world" &

means you need to wait the end of sleep before echoing anything and if echo fails the process stops but the whole command is backgrounded also. see complete explanation

Conclusion
the first syntax is shell script which means it's considering instructions separately as a list.
The second option uses && means AND so if you use it iof the first command fail the second will not be executed.

This is just different behaviour in handling errors.

user
  • 28,901
Kiwy
  • 9,534