User account management script in Bash Scripting - Time & Space Complexity
When running a user account management script, it is important to understand how the time it takes grows as the number of users increases.
We want to know how the script's work changes when managing more user accounts.
Analyze the time complexity of the following code snippet.
#!/bin/bash
users=("alice" "bob" "carol" "dave")
for user in "${users[@]}"; do
id "$user" >/dev/null 2>&1
if [ $? -ne 0 ]; then
useradd "$user"
fi
passwd -l "$user"
done
This script checks if each user exists, adds them if not, and then locks their password.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each user in the list.
- How many times: Once for each user in the users array.
As the number of users grows, the script runs the same steps for each user one after another.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and updates |
| 100 | About 100 checks and updates |
| 1000 | About 1000 checks and updates |
Pattern observation: The work grows directly in proportion to the number of users.
Time Complexity: O(n)
This means the time taken grows linearly with the number of users to manage.
[X] Wrong: "The script runs in constant time no matter how many users there are."
[OK] Correct: Because the script does work for each user, more users mean more work and more time.
Understanding how scripts scale with input size shows you can write efficient automation that handles growing tasks smoothly.
"What if the script also checked each user's group memberships inside the loop? How would the time complexity change?"