1

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
26.3k1 gold badge27 silver badges64 bronze badges
asked Apr 20, 2020 at 4:25
1

1 Answer 1

2

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.

answered Apr 20, 2020 at 4:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.