Read a single line with "read" in bash, but without "while"

I tried to understand how “while read” works in bash, and I came up with a behavior that I cannot explain:

root@antec :/# var=old_value root@antec :/# echo "new_value" | read var && echo $var old_value root@antec :/# 

It works fine with "while read":

 root@antec :/# var=old_value root@antec :/# echo "new_value" | while read var; do echo $var; done new_value root@antec :/# 

Can someone explain why it does not work when reading is used without yet? Moreover, I do not understand how the value of "var" in the main shell can be seen from the supposedly subshell after the pipe.

thanks

+6
source share
4 answers

I believe that this is a priority issue, with | having a higher priority than & &. First grouped as:

 (echo "new_value" | read var) && echo $var 

The second is grouped as:

 echo "new_value" | (while read var; do echo $var; done) 
+5
source

Why do you think this works in the second case? It really does not update var . do echo $var after the line with while and see ..

Explanation: everything that comes after | , is executed in a subshell that has its own copy of var . The var original is not affected in any case. What an echo depends on whether echo is called in the same subshell that does read or not.

+6
source

You do not need a while :

 echo "new_value" | (read var; echo $var) 
+1
source

I did not want to print the variable immediately, but use it later, and this works:

 var=old_value read var < <(echo "new_value") echo $var > new_value 

as an alternative:

 var=old_value tmp=$(echo "new_value") read var <<<"$tmp" echo $var > new_value 
0
source

Source: https://habr.com/ru/post/893822/


All Articles