Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

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.

share|improve this answer

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.

share|improve this answer
    
@terdon Thanks for the edit, My post was indeed terribly written –  Kiwy Nov 28 '13 at 16:04

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.