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
there
$ echo $var2
are
$ echo $var3
3 arguements
$REPLY
$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 |
Prompt
Create interactive prompt with -p
.
$ read -p "Enter username:"
Enter username: joe
$
Delimiters
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
secretpassword
$
Use unset <variable>
to remove user input
Character limit
Option -n
to set the character limit.
$ read -n 5
12345$
The command exits automatically after the 5 characters.
-N
set the character limit while ignoring the delimiter.
Timeout
Set a timeout on read to limit taken to input text.
read -t 2
Arrays
Use array instead of variables to store string.
$ read -a arr <<< "Hello world!"
$ echo ${arr[0]}
Hello
$ echo ${arr[1]}
world!
$