How to use read command in bash?

When I try to use the read command in Bash as follows:

 echo hello | read str echo $str 

Nothing happened again, although I think str should contain the string hello . Can someone help me understand this behavior?

+49
bash builtin built-in
Oct 06 2018-11-11T00:
source share
8 answers

read in your command script is ok. However, you execute it in the pipeline, which means that it is in a subshell, so the variables that it reads are not visible in the parent shell. You can either

  • also move the rest of the script to a subshell:

     echo hello | { read str echo $str } 
  • or use command substitution to get the value of a variable from a subshell

     str=$(echo hello) echo $str 

    or a slightly more complex example (capturing the second ls element)

     str=$(ls | { read a; read a; echo $a; }) echo $str 
+54
Oct 06 2018-11-11T00:
source share

Other bash alternatives that do not include a subshell:

 read str <<END # here-doc hello END read str <<< "hello" # here-string read str < <(echo hello) # process substitution 
+36
Oct 06 '11 at 3:15 a.m.
source share

A typical use might look like this:

 i=0 echo -e "hello1\nhello2\nhello3" | while read str ; do echo "$((++i)): $str" done 

and conclusion

 1: hello1 2: hello2 3: hello3 
+8
Oct 06 2018-11-11T00:
source share

The value disappears as the read command runs in a separate subshell: Bash FAQ 24

+3
06 Oct '11 at 15:00
source share

To place my two cents here: on KSH, read ing, as well as on a variable, will work, because according to the IBM AIX documentation , KSH read affects the current shell environment:

Setting shell variables using a read command affects the current shell runtime.

This led me to spend a lot of minutes figuring out why the single-line finale with read , which I used a million times before I didn't work on AIX on Linux ... is because KSH saves to the current environment and BASH does not work!

+2
Apr 04 '14 at
source share

I really use read only with "while" and do loop:

 echo "This is NOT a test." | while read -rabc theRest; do echo "$a" "$b" "$theRest"; done 

This is a test.
For what it's worth, I saw a recommendation to always use -r with a read command in bash.

0
Jul 19 '17 at 17:20
source share

Another alternative is to use the printf function.

 printf -v str 'hello' 

In addition, this design, combined with the use of single quotes, where appropriate, helps to avoid problems with multiple shoots of subshells and other forms of interpolation citation.

-one
Apr 04 '14 at 23:16
source share

Do you need a pipe?

 echo -ne "$MENU" read NUMBER 
-5
Oct 06 2018-11-15T00:
source share



All Articles