0
0
Bash Scriptingscripting~5 mins

User account management script in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: User account management script
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of users grows, the script runs the same steps for each user one after another.

Input Size (n)Approx. Operations
10About 10 checks and updates
100About 100 checks and updates
1000About 1000 checks and updates

Pattern observation: The work grows directly in proportion to the number of users.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows linearly with the number of users to manage.

Common Mistake

[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.

Interview Connect

Understanding how scripts scale with input size shows you can write efficient automation that handles growing tasks smoothly.

Self-Check

"What if the script also checked each user's group memberships inside the loop? How would the time complexity change?"