How to Read From Stdin in Bash? [4 Cases With Examples]

In Bash scripting, reading input from the standard input (stdin) is a common task. Whether you are collecting user data, processing commands, or building interactive scripts, understanding how to read from stdin is essential. Bash provides different ways to interactively read stdin from the user or from another command. In this writing, I will discuss the basics of stdin, and how you can read from stdin with some practical bash script examples.

Key Takeaways

  • Learning basics about Stdin & different input sources.
  • Practicing bash script examples of different ways to read from stdin.

Free Downloads

What is Stdin?

Stdin, short for ‘Standard input’, is an input stream where data is sent to and read by a program. It is generally represented by the file descriptor ‘0’. The default stdin is read from the keyboard.  Besides the keyboard, the stdin can be read from different input sources too. For that skim through the following list from where inputs can be sourced.

Different Stdin Sources in Bash

In the context of Bash, input refers to the data or information that a program receives or reads. And, when it comes to a bash script, inputs can be read from various sources:

  • Environment variables: These variables are inherited from the parent process that started the script & hold information that can be used in the execution of the scripts.
  • Command-line arguments: These are the values or options provided to the script when it’s executed. Generally, they are stored in the positional parameters.
  • Files: Inputs can be read from files. Scripts can read & extract relevant information from these files for further processing.
  • File Descriptors: A file descriptor is a system used to access various types of input sources, such as pipes, terminals, sockets, etc. These sources provide a way to receive input into the script.
  • Here Document (‘<<’): A here document allows you to input directly within a script.

4 Cases of Read From Stdin in Bash

In Bash, reading user input is a crucial aspect of creating interactive scripts, which allows scripts and programs to accept data from users directly from the keyboard or other input sources. In the following article, I will discuss 4 cases through which you can read from stdin.

Case 1: Reading From Stdin With “read” Command in Bash

The ‘read’ command is a built-in command in Bash used to read input from the user or from a specified input source. It then assigns the entered value to one or more variables for further script processing. Here, I will discuss 4 examples of how you can read from stdin using the read command.

Example 1: Basic “read” Command Usage

In this first example, I will show how you can simply use the ‘read’ command to read a single user input. To check the entire process practically, please follow the below steps:

Steps to Follow >

❶ At first, open your Ubuntu Terminal application.

❷ Now, open a file, let’s say, named ‘intro.sh’ in the nano editor by using the following command:

nano intro.sh

➌ Next, write the following script inside the Bash file in the nano text editor:

#! /bin/bash

echo "What’s your name?"
read name
echo "Hello, $name! Nice to meet you."

EXPLANATION
In the script’s first line, ‘#!’ is shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s Bash situated in the /bin directory. Next, the echo command echoes the quoted message. After that, the “read command” reads & stores the input from the user and assigns it to the variable “name”. In the last line, the echo command echoes the value previously stored in the “name” variable and other parts of the message.

➍ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.

➎ After that, use the following command to make the script executable:

chmod u+x intro.sh

EXPLANATION
  • chmod: Changes the permission of files and directories.
  • u+x: Argument with chmod command to add the executable permission for the user.
  • intro.sh: File which you want to make executable.

➏ Finally, run the script by the following command:

./intro.sh

Read from stdin using read command in bashThe script shows a user interactive message ‘What’s your name?’. Later it is read & displayed after the user has inserted the value ‘Joy’.

Example 2: Reading Multiple Values From Stdin

Bash can read multiple variables at a time. For that, just provide a list of variable names separated by spaces, and the command will assign the corresponding inputs to each variable. See the below script for a practical purpose:

You can follow the Steps of Example 1, to see how to save,  make the script executable, and run it.

Script (info.sh) >

#! /bin/bash

echo "Enter your name, age, and gender: "
read name age gender

echo "Name: $name"
echo "Age: $age"
echo "Gender: $gender"

EXPLANATION

First, the ‘echo command’ prints a prompt message to the user, specifying the inputs expected. After that, The ‘read’ command reads the user’s input, which is then executed to contain three values separated by spaces. It assigns these values to the variables ‘name’, ‘age’, & ‘gender’ respectively.  The next three lines display the value stored in these variables.

Read from multiple stdin in bash The script shows a user interactive message for multiple inputs. Later these values have been read & displayed after the user has inserted the values ‘joy 20 male’ (separated by space).

Example 3: Reading Into Variables in Bash

You can assign values to one or more variables after reading values from stdin using the read command. Read the following script for inspecting:

You can follow the  Steps of Example 1, to see how to save,  make the script executable, and run it.

Script (var.sh) >

#! /bin/bash

echo "Enter your name: "

read -p "Name: " name
echo "Hello, $name! Nice to meet you!"

EXPLANATION
The script starts with a message ‘Enter your name: ’ to be echoed. After that, the ‘read -p “Name: ” name’ line uses the read command with the ‘- p’ option to display a prompt, asking the user to enter their name.

Read multiple stdin using read commandFrom the image you can see, that the assigned variable value (Munny) is read & then displayed successfully.

Example 4: Reading Passwords Securely

You can assign any sensitive user information using the ‘read’ command with the option ‘–silent’ or ‘-s’ as the command option hides them without being displayed on the screen.

You can follow the  Steps of Example 1, to see how to save,  make the script executable, and run it.

Script (password.sh) >

#! /bin/bash

#Prompt to user to enter password without displaying input
echo -n Enter your password:
read -s password

#Move to a new line after the password input
echo
# Perform actions in silent mode
echo "Password entered: $password"

EXPLANATION

The first line ‘echo -n “Enter your password: ”’, echoes the quoted message with, -n being used to prevent a newline character from being added. Then in ‘read -s password’, the option ‘-s’ lets operate the “read” command in silent mode. Thus, the user can enter a password without displaying the characters on the screen. After that “echo” prints a ‘newline’ just to maintain the readability. Finally, ‘echo “Password entered: $password”’, prints out the password that the user entered.

Running bash script for user password inputThe script shows a user interactive message ‘Enter your password’. Later, the user enters the password but the command reads it in ‘silent mode’ without displaying it. Which you can see after printing the value.

Case 2: Reading Stdin From a File in Bash

You can redirect stdin to read data from a file using the input redirection operator ‘<’. Check out the following two bash script examples based on the way to read input from a file.

Example 1: Reading Line by Line From a File

You can use the ‘read’ command within a loop to process each line of a file. In this case, the script will simply echo each line with a processing message, but you can perform any desired operations.

You can follow the  Steps of Example 01 of case 01, to see how to save,  make the script executable, and run it.

Script (file.sh) >

#! /bin/bash

filename="input.txt"
while IFS= read -r line
do
   echo "Processing: $line"
   # Perform actions on each line
done < "$filename"

EXPLANATION
First, assign the file name you want to read from to the variable ‘filename’. Here, the file name is set to ‘input.txt’. Make sure the file exists in the same directory as the script or provide the full path to the file.

Then, the ‘while IFS=read -r line’ line initiates a ‘while’ loop that iterates over each line of the file. In the ‘IFS=read -r line’, the ‘read’ command reads each line from the file and assigns it to the variable ‘line’. By setting ‘IFS= ’ and using the ‘-r’ option it is ensured that leading & trailing whitespaces are preserved, and backlashes are not interpreted as escape characters. And ‘do’ sets actions for the command.

After that, ‘echo “Processing: $line”’, this line prints the current line being processed. Lastly, ‘done < “$filename”, this line redirects the contents of the file specified by the ‘$filename’ variable as input for the ‘while’ loop. Each line of the file will be read and processed until the end of the file is reached.’

Read stdin from a file in bashFrom the image you can see, that the script is reading & processing each line of the file ‘input.txt’. After reading, it is also displaying them one by one.

Example 2: Reading Entire File Content in Bash

You can also view the entire file content instead of displaying & processing line by line. Go through the below script for the practical observation:

You can follow the Steps of Example 01 of case 01, to see how to save,  make the script executable, and run it.

Script (entire_file.sh) >

#! /bin/bash

file="input.txt"
content=$(<"$file")

echo "$content"

EXPLANATION
In the script ‘file=”input.txt”’ defines a variable named ‘file’ and sets it to the string ‘input.txt’, which is the filename you want to read. After that, ‘content=$(<“$file”)’ reads the contents of the file specified by the ‘file’ variable (here ‘input.txt’) and stores those contents in the ‘content variable’, and then prints those contents to the terminal screen using the echo command.

read entire file contents See from the above image, the script displays the entire content of the ‘input.txt’ file.

Case 3: Reading From Piped Stdin in Bash

Bash can read input from pipelines, which allows you to chain commands together. For example, see the below script:

You can follow the Steps of Example 01 of case 01, to see how to save,  make the script executable, and run it.

Script (piped.sh) >

#! /bin/bash

echo "Enter some text: "
read input
echo "$input"  | grep "Hello"  

EXPLANATION
The script starts by displaying a prompt to the user to enter some texts. The read command reads a single line of input from the user. The value entered by the user is then piped (‘|’) to the ‘grep command’, which filters lines containing ‘Hello’ from the input.

read from piped stdin I ran the script twice so that you can see the difference between the outputs. At first, I entered one line of text containing the word ‘Hello’. As the grep command found the searched match, the line was echoed. But the second time, I entered one line of text without the word ‘Hello’. So the script doesn’t show any output rather a new command prompt appears.

Case 4: Reading From Stdin Using Here Documents in Bash

A here document is a block of code or text used as a way to pass input to a command within a script. To use here-document in any bash script you have to use the ‘<<’ operator followed by a delimiting identifier (here used, End of File or EOF) after any Bash command & then use the same delimiter again at the end of the text. Check out the following script for inspecting practically.

You can follow the Steps of Example 01 of case 01, to see how to save,  make the script executable, and run it.

Script (diff_file.sh) >

#! /bin/bash

sort <<EOF
923
854
111
245
109
476
909
EOF

EXPLANATION
In this script, a here document is used to provide the input numbers (923, 854, 111, 245, 109, 476, 909) to the sort command. The command will read these numbers from stdin & will sort ascendically by default.

read from stdin using here documents in bashSee from the image, the script displays the sorted output numbers of the provided input numbers using the here documents.

Conclusion

So far, you have understood how to read from Stdin in several cases in Bash. Just select the process that meets all your requirements and perform your task smoothly while working with Bash scripts.

People Also Ask

What is stdin in shell script?

Stdin stands for Standard Input, which is a data stream. A data stream helps to transfer data from a source to an outflow & vice versa. By default, it reads input from from the keyboard (i.e., user input from the terminal). However, you can redirect stdin to read from files, pipes, or other sources too.

What Bash command allows you to read input from stdin?

The ‘read command’ in Bash allows you to interactively read input from users. It reads from stdin & stores it in a variable or processes it within a script.

How to read input in bash?

In Bash, you can read input from various sources, such as the user, pipelines, or files, using the ‘read command’ or redirecting standard input (stdin).

What does @$ mean in bash?

In Bash scripting, ‘@$’ is not meaningful syntax. However, ‘$@’ refers to all the command-line arguments passed to a script or function as individual arguments. It treats each argument as a separate entity.

Related Articles


<< Go Back to Bash RedirectionBash Redirection and Piping | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Monira Akter Munny

Hello!! This is Monira Akter Munny. I'm a Linux content developer executive here, at SOFTEKO company. I have completed my B.Sc. in Engineering from Rajshahi University of Engineering & Technology in the Electrical & Electronics department. I'm more of an online gaming person who also loves to read blogs & write. As an open-minded person ready to learn & adapt to new territory, I'm always excited to explore the Linux world & share it with you! Read Full Bio

Leave a Comment