Options & Arguments
The read builtin command is used to read a single line of standard input.read [-options] [variable...]
- If no variable name is supplied, the shell variable
REPLYcontains the line of data. | Option | Description | | —- | —- | | -a array | Assign the input to array, starting with index zero. | | -d delimiter | The first character in the string delimiter is used to indicate the end of input, rather than a newline character. | | -e | Use Readline to handle input. This permits input editing in the same manner as the command line. | | -i string | Use string as a default reply if the user simply presses enter. Requires the -e option. | | -n num | Read num characters of input, rather than an entire line. | | -p prompt | Display a prompt for input using the string prompt. | | -r | Raw mode. Do not interpret backslash characters as escapes. | | -s | Silent mode. Do not echo characters to the display as they are typed. This is useful when inputting passwords and other confidential information. | | -t seconds | Timeout. Terminate input after seconds. read returns a non-zero exit status if an input times out. | | -u fd | Use input from file descriptor fd, rather than standard input. |
Examples
Read single variable
# read_single.shecho -n 'Please enter an interger: 'read intVar...
Read multiple variables
#!/bin/bash
# read_multiple.sh
echo -n 'Please enter multiple values: '
read var1 var2 var3 var4 var5
echo "var1 = $var1"
echo "var2 = $var2"
echo "var3 = $var3"
echo "var4 = $var4"
echo "var5 = $var5"
#!/bin/bash
# read_multiple.sh
Please enter multiple values: 1 2 3 4 5 6 7 8
var1 = 1
var2 = 2
var3 = 3
var4 = 4
var5 = 5 6 7 8
Default variable name REPLY
#!/bin/bash
# read_def_varname.sh
echo -n 'Please enter one or more values: '
read
echo "REPLY = $REPLY"
Default value
#!/bin/bash
# read_def_varvalue.sh
read -e -p "What is your user name? " -i $USER
echo "You answered: '$REPLY'"
$ read-default
What is your user name? ronnie
You answered: 'ronnie'
IFS
IFS — Internal Filed Separator
The default value of IFS contains a space,
a tab, and a newline character, each of which will separate items from one
another.
#!/bin/bash
# read_ifs.sh
read -p "Enter a username > " user_name
file_info=$(grep "^$user_name:" /etc/passwd)
IFS=":" read user pw uid gid name home shell <<< "$file_info"
