With regard to the below commands:
$ unset a
$ echo 12 | read a
$ echo $a
$
I was expecting that a would be set the value of 12 in the second statement. But it turns out that a is still unset.
-
I would recommend taking a look at this post. unix.stackexchange.com/questions/382391/what-does-unset-donullnv0id– nullnv0id2020年04月20日 04:29:14 +00:00Commented Apr 20, 2020 at 4:29
1 Answer 1
You can use Process Substitution in bash.
read -r a < <(echo 12)
echo "$a"
Or a here string
also in bash.
read -r a <<< 12
echo "$a"
In most shells, each command of a pipeline is executed in a separate SubShell. see Why I can't pipe data to read.
You need to use a temp file if the shell you're using does not support Process Substitution and a here string
echo 12 > tempfile
read -r a < tempfile
echo "$a"
Although tempfile is just an example for real life situation scripts a fifo
or mktemp
is used and created in a secure manner.