/etc/passwd and /etc/shadow in Linux CLI - Time & Space Complexity
When working with system files like /etc/passwd and /etc/shadow, it is important to understand how the time to read or search these files grows as they get larger.
We want to know how the time to find user information changes when the number of users increases.
Analyze the time complexity of the following command sequence.
# Search for a username in /etc/passwd
username="alice"
grep "^${username}:" /etc/passwd
# Search for the same username in /etc/shadow
grep "^${username}:" /etc/shadow
This code looks for a specific user's entry by scanning each line of the files /etc/passwd and /etc/shadow.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line of the file one by one to check if it matches the username.
- How many times: Once for each line in the file, until the username is found or the file ends.
As the number of users (lines) in the file grows, the time to find a username grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 line checks |
| 100 | Up to 100 line checks |
| 1000 | Up to 1000 line checks |
Pattern observation: The time grows steadily as the file gets longer, because each line is checked one after another.
Time Complexity: O(n)
This means the time to find a user grows linearly with the number of users in the file.
[X] Wrong: "Searching for a username is instant no matter how many users there are."
[OK] Correct: The system reads each line until it finds the username, so more users mean more lines to check, which takes more time.
Understanding how searching through system files scales helps you reason about performance in real scripts and automation tasks.
"What if the file was indexed or stored in a database instead? How would the time complexity change?"