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.

Kartikeya Sinha
  • 508
  • 1
  • 5
  • 20
  • It doesn't stuck, just press enter. – anubhava May 07 '14 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. – Kartikeya Sinha May 07 '14 at 14:31
  • 2
    Try this nohup command: `nohup bash b.sh > /tmp/log 2>&1 &` – anubhava May 07 '14 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? – Kartikeya Sinha May 07 '14 at 14:38
  • Not sure from which script you tool it but I have provided you right syntax for it – anubhava May 07 '14 at 15:26

1 Answers1

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.

Community
  • 1
  • 1
that other guy
  • 116,971
  • 11
  • 170
  • 194