su (switch user) in Linux CLI - Time & Space Complexity
We want to understand how the time it takes to switch users with su changes as we use it more or with different inputs.
Specifically, how does the command's execution time grow when switching users repeatedly or with different user data?
Analyze the time complexity of the following command usage.
for user in user1 user2 user3 user4 user5; do
su - $user -c 'echo Hello from $(whoami)'
done
This script switches to each user in a list and runs a simple command to print a greeting.
Look at what repeats in the script.
- Primary operation: The
sucommand runs once per user in the list. - How many times: It runs exactly as many times as there are users (5 times here).
Each time we add one more user to the list, the script runs su one more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times running su |
| 100 | 100 times running su |
| 1000 | 1000 times running su |
Pattern observation: The total work grows directly with the number of users; doubling users doubles the work.
Time Complexity: O(n)
This means the time to run the script grows in a straight line with the number of users you switch to.
[X] Wrong: "Switching users with su takes the same time no matter how many users I switch to."
[OK] Correct: Each su command runs separately, so more users mean more commands and more total time.
Understanding how repeated commands scale helps you write scripts that run efficiently and predict how long tasks will take.
What if we replaced the simple echo command with a longer script inside su -c? How would that affect the time complexity?