Making scripts executable (chmod +x) in Bash Scripting - Time & Space Complexity
Let's explore how the time it takes to make a script executable changes as the number of scripts grows.
We want to know how the work increases when we use chmod +x on many files.
Analyze the time complexity of the following code snippet.
for file in *.sh; do
chmod +x "$file"
done
This script loops over all files ending with .sh and makes each one executable.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
chmod +xcommand inside the loop. - How many times: Once for each
.shfile found.
As the number of script files grows, the total time grows in a similar way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times running chmod +x |
| 100 | 100 times running chmod +x |
| 1000 | 1000 times running chmod +x |
Pattern observation: The work grows directly with the number of files; double the files, double the work.
Time Complexity: O(n)
This means the time to make scripts executable grows linearly with the number of files.
[X] Wrong: "Running chmod +x on many files takes the same time as on one file."
[OK] Correct: Each file needs its own permission change, so more files mean more time.
Understanding how simple loops affect execution time helps you explain script performance clearly and confidently.
"What if we used a single chmod +x *.sh command instead of a loop? How would the time complexity change?"