SSH automation in Bash Scripting - Time & Space Complexity
When automating SSH commands in a script, it is important to understand how the time taken grows as we connect to more servers or run more commands.
We want to know how the script's running time changes when the number of servers or commands increases.
Analyze the time complexity of the following code snippet.
servers=("server1" "server2" "server3")
for server in "${servers[@]}"; do
ssh "$server" "uptime"
done
This script connects to each server in the list and runs the "uptime" command remotely.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs the ssh command once per server.
- How many times: Exactly once for each server in the list.
As the number of servers increases, the script runs the ssh command more times, one per server.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 ssh connections and commands |
| 100 | 100 ssh connections and commands |
| 1000 | 1000 ssh connections and commands |
Pattern observation: The total work grows directly in proportion to the number of servers.
Time Complexity: O(n)
This means the time to complete the script grows linearly as you add more servers to connect to.
[X] Wrong: "Running ssh commands in a loop is instant and does not depend on the number of servers."
[OK] Correct: Each ssh connection takes time, so more servers mean more total time spent connecting and running commands.
Understanding how your script's running time grows with more servers helps you write efficient automation and shows you can think about scaling tasks in real environments.
"What if we ran multiple commands per server inside the ssh session? How would the time complexity change?"