Here strings (<<<) in Bash Scripting - Time & Space 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?
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.
- 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.
As the length of each here string grows, the time to process it grows roughly in direct proportion.
| Input Size (characters) | Approx. Operations |
|---|---|
| 10 | About 10 operations to read the string |
| 100 | About 100 operations to read the string |
| 1000 | About 1000 operations to read the string |
Pattern observation: The work grows linearly with the size of the input string.
Time Complexity: O(n)
This means the time to process the here string grows directly with the length of the string.
[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.
Understanding how input size affects script commands like here strings helps you write efficient scripts and explain your reasoning clearly in real situations.
"What if we replaced here strings with reading from a file? How would the time complexity change?"