Docs  >   Bash Handbook   >   Reading-user-input

Top

Reading User Input

The user can enter data into shell variables using read commands.

read

This command reads input from stdin into variables

read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars]
     [-p prompt] [-t timeout] [-u fd] [variable1 ...] [variable2 ...]

If no variable names are provided, the user input is stored in the variable $REPLY by default.

#!/bin/bash

read          #Waits for user input
echo $REPLY   #Prints the text
Short Name Description
-a array Store the words in an indexed array named $array
-e Read data from terminal character by character till the delimiter is reached
-d delimiter Set the delimiting character to delimiter specified
By default, newline('\n') is the delimiter
-n nchars Stop reading when n characters or delimiter is read
-N nchars Stops reading only when n charaters or EOF is read, ignores delimiter
-p prompt Prints prompt string on console
-i interactive Prints placeholder text which user can modify
Used in conjunction with -e
-r raw input Disable shell interpretation of special charaters like $ and *
-s silent Disable echo of characters read onto terminal
-t timout Waits for certain amount of time before exitting
-u file descriptor Reads input from file descriptor specified
#!/bin/bash
read -p 'Enter your name: ' name
echo Hello, "$name"!

read -sp 'Enter Password: ' password
if [ "$password" == "1234" ]; then #Space around '[' is required
  echo -e "\nSuccess!"
else
  echo -e "\nTry Again!"
fi
echo ""
read -p "Enter numbers: " -a array
echo ${array[2]}

This script will produce such output:

Enter your name: User1
Enter password:
Success #if password entered was 1234

Enter numbers: 100 200 300 400
300