Silent input with read -s (passwords) in Bash Scripting - Time & Space Complexity
We want to understand how the time taken by a bash script changes when it asks for a password silently using read -s.
How does the script's running time grow as the password length changes?
Analyze the time complexity of the following code snippet.
#!/bin/bash
echo "Enter your password:"
read -s password
echo "\nPassword length is ${#password}"
This script asks the user to enter a password silently (no characters shown), then prints the password length.
Look for loops or repeated steps in the code.
- Primary operation: Reading each character typed by the user silently.
- How many times: Once per character in the password until Enter is pressed.
As the password gets longer, the script waits for more characters to be typed.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character reads |
| 100 | 100 character reads |
| 1000 | 1000 character reads |
Pattern observation: The time grows directly with the number of characters typed.
Time Complexity: O(n)
This means the time to read the password grows linearly with its length.
[X] Wrong: "The silent input happens instantly no matter how long the password is."
[OK] Correct: Each character must be typed and read one by one, so longer passwords take more time.
Understanding how input reading scales helps you write scripts that handle user input efficiently and predict how they behave with different input sizes.
"What if we changed read -s to read without silent mode? How would the time complexity change?"