In this final step, you will learn two more advanced techniques:
-
Reading secure input (like passwords) without displaying the characters on screen
-
Reading multiple variables with a single read command
-
Open your script for editing:
nano input_reader.sh
-
Replace the existing content with the following code:
#!/bin/bash
## Script demonstrating secure input and multiple variable reading
## Secure input reading with -s flag (no echo)
echo "Secure Input Example:"
read -p "Username: " username
read -s -p "Password: " password
echo ## Add a newline after password input
echo "Username entered: $username"
echo "Password length: ${#password} characters"
## Reading multiple variables at once
echo -e "\nMultiple Variable Example:"
read -p "Enter first name, last name, and age (separated by spaces): " first_name last_name age
echo "First name: $first_name"
echo "Last name: $last_name"
echo "Age: $age"
## Reading with a custom delimiter
echo -e "\nCustom Delimiter Example:"
read -p "Enter comma-separated values: " -d "," value1
echo ## Add a newline
echo "First value before comma: $value1"
echo -e "\nThank you for completing this lab on Linux input reading!"
This script:
- Uses the
-s flag with read to hide the input (useful for passwords or other sensitive information)
- Shows how to read multiple variables from a single line of input by providing multiple variable names to the
read command
- Demonstrates the
-d flag to specify a custom delimiter (instead of the default newline character)
-
Save the file by pressing Ctrl+O, then press Enter to confirm the filename, and exit nano by pressing Ctrl+X.
-
Run the script to test it:
./input_reader.sh
Example output (your inputs will be different):
Secure Input Example:
Username: john_doe
Password:
Username entered: john_doe
Password length: 8 characters
Multiple Variable Example:
Enter first name, last name, and age (separated by spaces): John Doe 30
First name: John
Last name: Doe
Age: 30
Custom Delimiter Example:
Enter comma-separated values: test,
First value before comma: test
Thank you for completing this lab on Linux input reading!
Security is important when handling sensitive information like passwords. The -s flag ensures that the characters typed are not displayed on the screen. Notice that in the password example, the script only shows the length of the password for verification, not the actual password.
Reading multiple variables at once can make your scripts more efficient and user-friendly. When the read command is given multiple variable names, it splits the input based on the IFS (Internal Field Separator) environment variable, which defaults to whitespace (spaces, tabs, and newlines).
The -d flag allows you to change the delimiter that signals the end of input. By default, read stops at a newline (when you press Enter), but you can change it to any character, like a comma in the example.