0
0
Bash Scriptingscripting~5 mins

Port scanning basics in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Port scanning basics
O(n)
Understanding Time Complexity

When we scan ports using a script, we want to know how long it takes as the number of ports grows.

We ask: How does the time to scan change when we check more ports?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for port in {1..1000}; do
  timeout 1 bash -c ">> /dev/tcp/127.0.0.1/$port" 2>/dev/null
  if [ $? -eq 0 ]; then
    echo "Port $port is open"
  fi
 done

This script tries to connect to each port from 1 to 1000 on localhost to see if it is open.

Identify Repeating Operations
  • Primary operation: The for-loop that tries to connect to each port one by one.
  • How many times: It runs once for every port in the range (e.g., 1000 times).
How Execution Grows With Input

Each port check takes about the same time, so total time grows as we add more ports.

Input Size (n)Approx. Operations
1010 connection attempts
100100 connection attempts
10001000 connection attempts

Pattern observation: The time grows directly with the number of ports checked.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of ports, the scanning time roughly doubles.

Common Mistake

[X] Wrong: "The script checks all ports at the same time, so time stays the same no matter how many ports."

[OK] Correct: The script checks ports one after another, so more ports mean more time.

Interview Connect

Understanding how loops affect time helps you explain script speed clearly and shows you can think about efficiency.

Self-Check

"What if we scanned multiple ports at the same time using background jobs? How would the time complexity change?"