0

I am trying to understand the reason behind the difference in redirections of bash output. Here are two approaches:

  1. Redirection of the output to named pipe: /bin/bash -i 2>&1 1>/tmp/fifo
  2. Redirection using unnamed pipe to another script reading from stdin: /bin/bash -i 2>&1 | ./reader.sh

reader.sh is supposed to read line by line from stdin:

while read LINE; do
   echo ${LINE}    # do something with it here
done
exit 0

The question is: Why when redirecting to fifo (approach#1) the prompt information (username@host: $) is not redirected, but when redirecting to another program/script (approach#2), it does? Approach 2:

2 Answers 2

2

Because when you have left | right, the shell arranges to run two child processes with the stdout of left connected to the stdin of right, and after that, the children process any redirections they have. So in left 2>&1 | right, the stdout of left is first redirected to the pipe, then the stderr of left is redirected to where it's stdout goes, i.e. the pipe.

In something 2>&1 > file, the redirections are processed from left to right, so first, stderr is redirected to where stdout goes (likely the terminal, so no change), then stdout is redirected to file.

So you likely want to swap the order of the redirections.

0

When bash is launched it tries to determine if it is interactive or not, so it executes the isatty() function.

From GNU bash documentation:

An interactive shell is one started without non-option arguments, unless -s is specified, without specifying the -c option, and whose input and output are both connected to terminals (as determined by isatty(3)), or one started with the -i option. See Section 6.3 [Interactive Shells], page 94, for more information

  1. Redirection to a named pipe: /bin/bash -i 2>&1 1>/tmp/fifo. As the named pipe is not connected to any tty, bash assumes that the session is not interactive and doesn't send prompt information.
  2. Redirection using unnamed pipe to another script reading from stdin: /bin/bash -i 2>&1 | ./reader.sh. When redirecting to another process using unnamed pipe, bash assumes being interactive. As a result the prompt is redirected as well.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.