I am trying to run the following, as a test for something else:

function echo_test {
  sleep 60 & > /dev/null
  echo $returnpid


echo "This was the value that was returned by the function:"
echo $pidthatwasreturned

The problem is that the function doesn't exit and return until the sleep has finished, even though it has been run in the background. In the script that I am developing, the sleep command will effectively be replaced by a long running command. Is there some way in which I can rewrite this function to get it to return immediately?

  • Try sleep 60 >/dev/null &. – jimmij Jan 29 '16 at 14:40

The function exits, but the shell set's up a pipe from the function to the code that reads from stdout of the function and then places the result into the variablepidthatwasreturned.

This stdout file descriptor however is held open by the sleep command for 60 seconds.

Your function redirects the output for the echo command but not for the sleep command and for this reason, the variable assignment waits until stdout from the sleepis closed.

If you exchange & and > /dev/null, it works in the Bourne Shell and should work in bash as well unless there is a bug in bash.

  • Thanks Schily. This had me scratching my head for a while :-) – Codemunger Jan 29 '16 at 15:45
  • @Codemunger If this answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Feb 4 '16 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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