FUNDAMENTALS A Complete Guide for Beginners
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:
❶ 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."
➍ 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
- 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
The 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"
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.
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!"
From 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"
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.
The 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"
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.’
From 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"
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"
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
See 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
Related Articles
- Bash Input Redirection [3 Practical Cases]
- What is Output Redirection in Bash [With 4 Practical Cases]
- How to Redirect Stderr in Bash [5 Practical Cases]
- How to Redirect Stdout and Stderr to File in Bash [5 Cases]
- Redirect Stderr to Stdout in Bash [5 Examples]
- 5 Ways to Echo to Stderr in Bash
<< Go Back to Bash Redirection | Bash Redirection and Piping | Bash Scripting Tutorial