0
0
Bash Scriptingscripting~5 mins

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

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

We want to understand how the time taken by a bash script using here strings changes as the input size grows.

Specifically, how does the script's work increase when the text inside the here string gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


read -r line1 <<< Hello
read -r line2 <<< World
read -r line3 <<< "This is a longer string"

# Print the lines
printf "%s\n" "$line1" "$line2" "$line3"
    

This script reads three strings using here strings and prints them. Each here string feeds a line of text to the read command.

Identify Repeating Operations
  • Primary operation: Each here string passes its entire text to the read command once.
  • How many times: The read command runs three times, once per here string.
How Execution Grows With Input

As the length of each here string grows, the time to process it grows roughly in direct proportion.

Input Size (characters)Approx. Operations
10About 10 operations to read the string
100About 100 operations to read the string
1000About 1000 operations to read the string

Pattern observation: The work grows linearly with the size of the input string.

Final Time Complexity

Time Complexity: O(n)

This means the time to process the here string grows directly with the length of the string.

Common Mistake

[X] Wrong: "Here strings run instantly no matter how big the input is."

[OK] Correct: The shell must still read and process every character in the here string, so bigger input takes more time.

Interview Connect

Understanding how input size affects script commands like here strings helps you write efficient scripts and explain your reasoning clearly in real situations.

Self-Check

"What if we replaced here strings with reading from a file? How would the time complexity change?"