Table of Contents

Bash - Read (Builtin Command) that capture a line

About

Read 1) is a bash builtin command and read:

from:

and:

You could read a csv

Example

Prompting a user

Without message

read myVar
hello

echo $myVar
hello

With message

read -p "Type Something: " myVar
Type Something: hello

echo $myVar
hello

Read from a standard input

Example on how to read from a standard input

echo "hello world" | { read foo; echo foo=$foo; }
read foo < <(echo "bar")
# The variable created is available in the same scope
echo foo=$foo;
read foo <<< "Hello World"; echo foo=$foo;
IFS=$'\n' read -r -a REPO_DIRS -d $'\c0' < /path/to/myfile.csv

Get the first two words (fields) of a line

Read parse the line with the IFS separators and assign the value to the names defined, we can then use it to parse a line.

Example

echo "hello world, how do you do ?" | { read foo bar mi; echo foo=$foo bar=$bar mi=$mi; }
foo=hello bar=world, mi=how do you do ?

echo "hello world, how do you do ?" | { IFS=" ," read foo bar mi; echo foo=$foo bar=$bar mi=$mi; }
foo=hello bar=world mi=how do you do ?

Loop line by line

This command:

ls -l | while read -r lineVariable; do
    echo Line: $lineVariable
done
Line: -rw-r--r-- 1 root root 1849173 May 13 2015 unixODBC-2.3.2.tar.gz
Line: -rwxr-xr-- 1 oracle oinstall 64 May 16 2017 whileDemo.sh

Syntax

read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...]

where:

Name assignment

The first word is assigned to the first variable name, the second word to the second name, and so on, If there are :

The characters in IFS are used to split the line into words. The backslash character (\) may be used to remove any special meaning for the next character read and for line continuation.

Return code

The return code is zero, unless: