1

I have a shell script which I want to invoke in background, from another shell script. Both the scripts are bash scripts.
First script(a.sh) is something like:

read a
echo 'something'
read b
echo 'something else'
# some if else conditions
nohup bash b.sh 2>&1 > /tmp/log &

When I try to execute the above script as: ./a.sh arg1 arg2 | tee log , very strangely it stucks at the nohup line for the second script b.sh to finish whereas it should not.

But when I just have the following line in the script, it works as expected:
nohup bash b.sh 2>&1 > /tmp/log &

Please help. I can also share the exact scripts if required.

5
  • It doesn't stuck, just press enter. Commented May 7, 2014 at 14:28
  • No. It's stuck. By stuck I mean it waits for the second script to finish. Obviously pressing enter would insert a new line at the stdout, but it is not out of the first script. Commented May 7, 2014 at 14:31
  • 2
    Try this nohup command: nohup bash b.sh > /tmp/log 2>&1 & Commented May 7, 2014 at 14:32
  • It worked ! Thanks a lot. But I am still unable to understand why it was happening. And when same line was there in a separate script(which had no other line) why it worked there and not here. Any suggestions? Commented May 7, 2014 at 14:38
  • Not sure from which script you tool it but I have provided you right syntax for it Commented May 7, 2014 at 15:26

1 Answer 1

2

This is what you wanted to happen:

  1. The script runs and output things
  2. The script runs a command in the background
  3. The script exits
  4. The pipe closes
  5. tee exits

This is what's happening:

  1. The script runs and outputs things
  2. The script runs a command in the background, with the pipe as stderr
  3. The script exits
  4. The pipe is still held open by the backgrounded command
  5. tee never exits.

You fixed it by pointing stderr to the log file rather than the pipe, so that the backgrounded process no longer keeps the pipe open.

The meaning of the order of 2>&1 and the redirect has been explained in other answers, and shellcheck would have automatically pointed out this problem in your code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's exactly what I needed. Would take care of the order in future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.