[Bash] Reading from Standard Input

To read from standard input in a Bash shell, use read. The following script reads content from stanard input and outputs the content:


# Uncomment this to use comma as a separator.
# IFS=","

read first second third
echo first=\"${first}\" second=\"${second}\" third=\"${third}\"

The call to read at line 6 will read a line and assign the words into the variables first, second and third. By default, it expects the words to be separated by the space character. Invoking the script with the input “a 2 c” will yield the output:

first="a" second="2" third="c"

Changing the delimiter

If the words are separated by other characters, set IFS (Internal Field Separator) to the character. In the above script, uncommenting line 4 and using the input “a, 2, c” will produce:

first="a" second=" 2" third=" c"

Notice that the output for second and third contain a leading space character. To have read exclude the space character, add the space character to IFS:

IFS=" ,"

Reading into an array

Use the -a flag to assign the read contents into an array instead of using separate variables. This is especically useful if the number of items is not known upfront. The script below uses read to put the contents in an array and outputs the contents:


read -a array 
echo Begin array contents:
    for item in ${array[@]}
        echo \"${item}\"
echo End array contents

Executing the script with contents “a 2 c” produces:

Begin array contents:
End array contents

Further reading

In the Linux man pages, the command is described in the page for Bash (it is listed under Shell Builtin Commands).


3 Responses to [Bash] Reading from Standard Input

  1. Dylan says:

    Huh. Thats really handy.. not that I’ve done much batch scripting since uni.

    • kahgoh says:

      Its especially handy when you are trying to write something that is supposed to take input from standard input, like the Git pre-receive and post-receive hooks (I wrote a post-receive hook for automatically pushing changes to other repositories – its posted on GitHub) … although I could’ve also written it in other scripting languages like Python, Perl, etc …

  2. Dylan says:

    haha ..or even BASH scripting (which is more relevant to this article) 😛

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: