0

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.

Freddy
  • 25,565
user15740
  • 103
  • I would recommend taking a look at this post. https://unix.stackexchange.com/questions/382391/what-does-unset-do – nullnv0id Apr 20 '20 at 04:29

1 Answers1

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.

Jetchisel
  • 1,264