Read from stdin in bash

Read from stdin in bash

To read input from stdin to a variable, namely inp. Use read command

IFS= read -r inp

-r flag is not a mandatory flag but is recommended in most cases.

From official read manual by typing help read from command line

-r do not allow backslashes to escape any characters

Refer to shell check SC2162 rule


Example

$ IFS= read my_var
#enter: hello\ world
$ echo "${my_var}"
#print: hello world

$ IFS= read -r my_var
#enter: hello\ world
$ IFS= echo "${my_var}"
#print: hello\ world

Bonus

To read space-delimited list of words and assign to an indexed array, add -a flag

$ IFS= read -r -a my_list #-a must follow after -r
#enter: hello\ world
$ IFS= echo "${#my_list[@]}" # print number of elements
2

$ IFS= read -a my_list
#enter: hello\ world
$ IFS= echo "${#my_list[@]}"
1

To read multiple lines and assign each line to an element of an array, use mapfile -t ( -t flag is recommended to remove trailing newline character)

$ mapfile -t my_list
#enter
#hi
#new world
#ctrl-D
$ echo ${#my_list[@]}
2
$ echo ${#my_list[0]}
2

$ mapfile my_list
#enter
#hi
#new world
#ctrl-D
$ echo ${#my_list[0]}
3

To redirect the standard input from a variable use <<< pipeline ( here strings)

$ mapfile -t my_list <<< "${my_var}"

Check my article about array variables in bash.

Buy Me A Coffee