0
0
Bash Scriptingscripting~5 mins

Here documents (<<EOF) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Here documents (<<EOF)
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a script with a here document changes as the input grows.

Specifically, how does the script's work increase when the here document content gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

cat <<EOF
Line 1
Line 2
Line 3
EOF

This script uses a here document to send multiple lines of text to the cat command, which prints them out.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading and printing each line from the here document.
  • How many times: Once for each line inside the here document.
How Execution Grows With Input

As the number of lines in the here document grows, the script reads and prints more lines.

Input Size (n lines)Approx. Operations
1010 reads and prints
100100 reads and prints
10001000 reads and prints

Pattern observation: The work grows directly with the number of lines; doubling lines doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows linearly with the number of lines in the here document.

Common Mistake

[X] Wrong: "The here document runs instantly no matter how many lines it has."

[OK] Correct: Each line must be read and processed, so more lines mean more work and more time.

Interview Connect

Understanding how input size affects script time helps you write efficient scripts and explain your reasoning clearly in interviews.

Self-Check

"What if the here document content was piped to a command that processes lines twice? How would the time complexity change?"