Linux Basic — Optimizing Scripts Practice
Practice Exercises — Optimizing Scripts
Measure, optimise, and measure again.
Warm-up
- Replace
cat file | grep patternwithgrep pattern file. - Replace
echo "$var" | cmdwithcmd <<< "$var". - Replace
if [ "$x" = "y" ]withif [[ "$x" == "y" ]]. - Replace
result=$(expr $a + $b)withresult=$((a + b)).
Builtins vs External
- Use
${file##*/}instead ofbasename "$file". - Use
${file%/*}instead ofdirname "$file". - Replace
for i in $(seq 1 1000)withfor i in {1..1000}. - Use
command -vinstead ofwhich.
Arrays
- Use
mapfile -t lines < fileto read a file into an array. - Refactor a loop that splits a string on every iteration to split once into an array.
Profiling
- Use
timeto measure a script’s real/user/sys time. - Use
/usr/bin/time -vto see memory usage (Linux). - Enable per-line tracing with
PS4and find the slowest line. - Use
SECONDS=0to time a function.
Parallelism
- Convert a serial loop that processes 100 files into
xargs -P 4. - Use
find -print0 | xargs -0for files with spaces. - Parallelise the same task with GNU
parallel -j 8 --bar. - Export a Bash function and call it from
parallel.
Real Scenario
- Take a script that runs
grepinside a loop over 1,000 files. Refactor to onegrep -rorxargs grep. - Take a 10-second script, profile it, identify the bottleneck, apply one optimisation from this chapter, and verify the speedup.
Verification Checklist
- Benchmarked before and after (
timeoutput) - No unnecessary forks in hot loops
- Builtins used where possible
- Parallelism applied to I/O-bound or CPU-bound independent tasks
-print0/-0used for safe filename handling
You’ve Completed Linux Basics!
You now have the tools to write correct, maintainable, and fast Bash scripts. From here:
- Build automation for your own workflows
- Contribute to open-source shell projects
- Explore advanced topics: network scripting, parsing complex formats, or bridging Bash with Python/Go
Keep scripting, and remember: clarity first, then correctness, then speed.