Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the read command in Bash?

Tags:

bash

built-in

When I try to use the read command in Bash like this:

echo hello | read str echo $str 

Nothing echoed, while I think str should contain the string hello. Can anybody please help me understand this behavior?

like image 297
Determinant Avatar asked Oct 06 '11 14:10

Determinant


People also ask

How does read work in bash?

Bash read SyntaxThe read command takes the user input and splits the string into fields, assigning each new word to an argument. If there are fewer variables than words, read stores the remaining terms into the final variable. Specifying the argument names is optional.

Why we use read in bash?

In Bash scripting, the “read” command is used to obtain input from users. Understanding the “read” command is key to making your code more interactive. The “read” command is used to obtain inputted information from the user.

How do I read a file in bash?

Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.


2 Answers

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

  • move the rest of the script in the subshell, too:

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

    str=$(echo hello) echo $str 

    or a slightly more complicated example (Grabbing the 2nd element of ls)

    str=$(ls | { read a; read a; echo $a; }) echo $str 
like image 200
jpalecek Avatar answered Sep 29 '22 09:09

jpalecek


Other bash alternatives that do not involve a subshell:

read str <<END             # here-doc hello END  read str <<< "hello"       # here-string  read str < <(echo hello)   # process substitution 
like image 20
glenn jackman Avatar answered Sep 29 '22 08:09

glenn jackman