Sujet : Re: Different variable assignments
De : jpstewart (at) *nospam* personalprojects.net (John-Paul Stewart)
Groupes : comp.unix.shellDate : 11. Oct 2024, 19:27:40
Autres entêtes
Message-ID : <lmt90sFr1idU1@mid.individual.net>
References : 1
User-Agent : Mozilla Thunderbird
On 2024-10-11 2:11 p.m., Frank Winkler wrote:
Hi there !
Consider the following commands:
$ var1=`uname -sr`
$ echo $var1
Darwin 24.0.0
$ read var2 <<< `uname -sr`
$ echo $var2
Darwin 24.0.0
$ uname -sr | read var3
$ echo $var3
$ uname -sr | read -p var3
$ echo $var3
$
While the first two ones behave like expected, I wonder why the latter
ones fail. What's the difference behind the scenes?
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.
And even more confusing, why does this familiar one work anyway?
$ sw_vers | while read line; do echo $line; done
ProductName: macOS
ProductVersion: 15.0.1
BuildVersion: 24A348
Here the subshell runs everything between 'while' and 'done' so the read
and echo commands are in the same (sub)shell this time.