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?
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With