Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Bash read command
  • Bash read examples
  • Conclusion

Bash read Command with Examples

Many times we want to make our script interactive. To do so, we take input from the user, pass it to the script to process it and acknowledge the output to the user. In this tutorial, we will look at examples of how to read user input in bash.

Bash read command

Bash has a built-in utility to read input from the user, named read. This command reads only a single line from bash shell. It assigns the values of each field in the input line to a shell variable. The characters in the IFS (Internal Field Separator) act as the separators for this assignment.

Syntax:

read <flag> <variable_name>

Bash read options

The read command provides us with a range of options as described below.

Flags
Description

-a ANAME

The words are assigned to sequential indexes of the array variable ANAME, starting at 0. All elements are removed from ANAME before the assignment. Other NAME arguments are ignored.

-d DELIM

The first character of DELIM is used to terminate the input line, rather than newline.

-e

readline is used to obtain the line.

-n NCHARS

read returns after reading NCHARS characters rather than waiting for a complete line of input.

-p PROMPT

Display PROMPT, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.

-r

If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.

-s

Silent mode. If input is coming from a terminal, characters are not echoed.

-t TIMEOUT

Cause read to time out and return failure if a complete line of input is not read within TIMEOUT seconds. This option has no effect if read is not reading input from the terminal or from a pipe.

-u FD

Read input from file descriptor FD.

Bash read examples

There are different ways of reading the input given by the user. The input could be given directly on the terminal or it can be provided in a given file which the script is supposed to read. The input could be in the form of multiple words too.

Example 1: Read user supplied input

A very simple and straightforward use of read command is to read the input provided by the user on the command line.

#!/bin/bashecho "Enter name"read nameecho "Hi, $name"echo "Do you want to read another name (Y/N)"read choiceif [ "$choice" == "Y" ]then echo "Enter another name" read name echo "Hello, $name"else echo "Input is not Y. Exiting" exit 1fi

Upon the execution of the script, the read command is asking for the user input. These inputs are getting stored in the variables passed along with the read command. Once the variables are assigned the respective values, they can be processed as per the requirements.

The script asks the user to enter the name. After printing the message it asks the user to enter a choice. If yes, it asks for another name. Otherwise it exits by displaying a message pointing out the fact that the choice entered is not Y.

Example 2: Read input from a file

Users can also provide input in a file.

#!/bin/bashfilename=sample1.txtwhile read linedo echo $linedone < $filename

If the input is huge, users often prefer to provide the input in a file. Each line of the input file is read using a while loop. It gets stored in the variable and then moves to the next line. The loop terminates after the last line has been processed.

The script is reading the input provided in the file line by line and displaying the output on the screen. For each iteration of the while loop, the read command reads that particular line of the file and assigns it to the bash shell variable $line. The loop runs till the number of lines in the file. After reading the last line of the file, the while loop stops.

Example 3: Read password input

We can also read input in the form of passwords.

#!/bin/bashread -p "Enter name " nameecho "Hi, $name"read -sp "Enter password " passechoecho "$name has provided the password $pass"

We can use the -s flag available with the read command to silent the echo from the user input. This allows working with the read command in a secure way. The input is silenced. As a result bash doesn’t display what the user is typing. However, that input is stored and can be retrieved later from the variable.

The script is taking username and password from the user. The password is silent and whatever the user types as password isn’t displayed. But it is stored in the variable and that variable is printed.

Example 4: Read input into multiple variables

The user input may not always be just a single word.

#!/bin/bashecho "Enter first and last name"read firstname lastnameecho "Good day $firstname and $lastname."

The user input is split to parts at white-space characters and these broken chunks are assigned to respective variables. Based on the input and the number of variables used with the read command the possible scenarios are:

Scenario
Outcome

Number of Words = Number of Variables

Variables are assigned to the respective words.

Number of Words < Number of Variables

Respective Words are assigned to the variables. Remaining variables remain empty.

Number of Words > Number of Variables

Respective Words are assigned to the variables. Except for the last variable which is assigned the rest of input.

The read command is expecting the first and the last name. If just one input is provided the latter is set to an empty string. If the input is more than two words, the last name is set to everything after the first name. Otherwise, the first word becomes the first name and the second word becomes the last name.

Example 5: Read input from command line arguments

The input can be passed as command line arguments to the script. They can be read directly by their positions and we don’t require the read command.

#!/bin/bashecho "Script Name: $0"echo "First Parameter of the script is $1"echo "The second Parameter is $2"echo "The complete list of arguments is $@"echo "Total Number of Parameters: $#"

The script will run with the arguments specified and use positional parameters to generate the output. We use command-line arguments to specify the position in memory where the command and the associated parameters are stored. There are special variables, saved numerically, reserved to point to the arguments ($1, $2, $3, … $n).

The first command-line argument is $1, the second $2 and so on. The variable $0 contains the name of the script. $# stores the total number of arguments. $@ and $* denote all the arguments.

Conclusion

  • Read command is a handy tool to develop scripts that accept input from the user and generate the output.

  • We can also use the read command to ask for sensitive data like passwords which we do not want to display on the screen while typing it.

  • We can read from the file too, especially for extremely long inputs.

PreviousBash Looping Through Array of StringsNextBash Check Empty Array

Last updated 1 year ago

read input mulitple variable
read password input
read input from command arguments
read user input
read input from a file