Sujet : Re: Different variable assignments
De : janis_papanagnou+ng (at) *nospam* hotmail.com (Janis Papanagnou)
Groupes : comp.unix.shellDate : 12. Oct 2024, 02:59:49
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vecl6n$d0r$1@dont-email.me>
References : 1 2 3
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.8.0
On 11.10.2024 20:45, Frank Winkler wrote:
On 11.10.2024 20:27, John-Paul Stewart wrote:
>I don't know about other shells, but in Bash each command in a pipeline
>is run in a subshell. (See the "Pipelines" section of the Bash man
>page.) Thus you're doing the 'read var3' part in a different shell than
>where 'echo $var3' runs. That's why it is empty when you echo it.
That sounds very plausible - thanks for enlighting! :)
So this is not a "read" issue but rather a matter of shell instance and
hence there's no way to do the assignment at the end?
It depends on your shell. If you choose Kornshell you won't have that
issue and can write it as you've done with the output as you'd expect.
$ uname -a | read var
$ echo "$var"
Linux [...snip...]
The reason is that the last command in a pipeline will (in Kornshell)
be executed in the "current" shell context.
(In other shells you have to work around the issue as demonstrated in
other answers to your post. Some workaround are more clumsy some less.
A shorter variant of the here-document posted elsethread can be using
here-strings
$ read var <<< $(uname -a)
another method is using process substitution and redirection
$ read var < <(uname -a)
Both supported by shells like ksh, bash, zsh, but non-standard as are
some other workaround proposals that use bash-specifics like 'coproc',
that doesn't work as widely as using '<<<' or '<(...)' do.)
Janis