August 30, 2022

Bash builtin Read

The bash read command is a built-in utility that read text from the standard input.

Bash Read Syntax

The syntax for read command is:

read <options> <arguements>

The read command reads a line from the standard input and split it into fields, assigning each word to an arguement. If there are leftover words, they are assigned to the last arguement.

$ read user_input
this is my text
$ echo $user_input
this is my text
$ read var1 var2 var3
there are 3 arguements
$ echo $var1
$ echo $var2
$ echo $var3
3 arguements


$REPLY is the default variable used by the read builtin.

$ read
this text will be stored in the variable $REPLY
$ echo $REPLY
this text will be stored in the variable $REPLY

Bash read options

options description
-a array assign the words read to sequential indices of the array variable ARRAY, starting at zero
-d delim continue until the first character of DELIM is read, rather than newline
-e use Readline to obtain the line
-i text use TEXT as the initial text for Readline
-n nchars return after reading NCHARS characters rather than waiting for a newline, but honor a delimiter if fewer than NCHARS characters are read before the delimiter
-N nchars return only after reading exactly NCHARS characters, unless EOF is encountered or read times out, ignoring any delimiter
-p prompt output the string PROMPT without a trailing newline before attempting to read
-r do not allow backslashes to escape any characters
-s do not echo input coming from a terminal
-t timeout time out and return failure if a complete line of input is not read within TIMEOUT seconds.
-u fd read from file descriptor FD instead of the standard input


Create interactive prompt with -p.

$ read -p "Enter username:"
Enter username: joe


By default, newline end the command. The option -d provide a different delimiter to terminate differently.

$ read -d -
hello world - $

Hidng input

Option -s to hide sensitive information input.

$ read  -p "Enter secret password: " -s password
Enter secret password: $ echo $password

Use unset <variable> to remove user input

Character limit

Option -n to set the character limit.

$ read -n 5

The command exits automatically after the 5 characters.

-N set the character limit while ignoring the delimiter.


Set a timeout on read to limit taken to input text.

read -t 2


Use array instead of variables to store string.

$ read -a arr <<< "Hello world!"
$ echo ${arr[0]}
$ echo ${arr[1]}

Powered by Hugo & Kiss.