5

I must be missing something very fundamental about the Bash read command. At the shell prompt, this fails to assign the three input fields to the corresponding variables:

% echo a b c | read x1 x2 x3
% echo $x1 $x2 $x3

% 

This works though:

% echo a b c | while read x1 x2 x3 ; do
> echo $x1 $x2 $x3
> done
a b c
%

I only have to read one line of input. Using a while loop is incorrect here, as I lose the values of x1, x2, and x3 when the loop's subprocess exits. I'd have to place all the code that accesses them within the loop body (and perhaps break at the end, for "clarity"), which seems very hackish. Using it within an if command works as well, but suffers from the same subprocess issues as a while loop:

% echo a b c | if read x1 x2 x3 ; then echo $x1 $x2 $x3; fi
a b c
% echo $x1

BASH_VERSION reports as "4.2.45(1)-release".

2
  • 1
    The first would work with this: read x1 x2 x3 <<< "a b c" Commented Sep 27, 2013 at 13:33
  • possible duplicate of Losing environment in while loop Commented Sep 27, 2013 at 14:03

2 Answers 2

11

The problem is the pipe. From bash manual:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

You have to do reverse, i.e., call read in current process and have input generated in subprocess. For example:

$ read x1 x2 x3 < <(echo a b c)
$ echo $x1 $x2 $x3
a b c
Sign up to request clarification or add additional context in comments.

1 Comment

+1 In bash 4.2, there is the option of shopt -s lastpipe, which will allow echo a b c | read x1 x2 x3 to work by allowing the last command of a pipeline to run in the current shell instead of a subshell.
2

read is a bash built-in command which is being run in a bash subprocess. It is setting the environmental variables within that subprocess, so when you check the values in the original process, nothing has been changed.

Comments

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.