Linux Basic — Optimizing Scripts Practice

1 minute read

Practice Exercises — Optimizing Scripts

Measure, optimise, and measure again.


Warm-up

  1. Replace cat file | grep pattern with grep pattern file.
  2. Replace echo "$var" | cmd with cmd <<< "$var".
  3. Replace if [ "$x" = "y" ] with if [[ "$x" == "y" ]].
  4. Replace result=$(expr $a + $b) with result=$((a + b)).

Builtins vs External

  1. Use ${file##*/} instead of basename "$file".
  2. Use ${file%/*} instead of dirname "$file".
  3. Replace for i in $(seq 1 1000) with for i in {1..1000}.
  4. Use command -v instead of which.

Arrays

  1. Use mapfile -t lines < file to read a file into an array.
  2. Refactor a loop that splits a string on every iteration to split once into an array.

Profiling

  1. Use time to measure a script’s real/user/sys time.
  2. Use /usr/bin/time -v to see memory usage (Linux).
  3. Enable per-line tracing with PS4 and find the slowest line.
  4. Use SECONDS=0 to time a function.

Parallelism

  1. Convert a serial loop that processes 100 files into xargs -P 4.
  2. Use find -print0 | xargs -0 for files with spaces.
  3. Parallelise the same task with GNU parallel -j 8 --bar.
  4. Export a Bash function and call it from parallel.

Real Scenario

  1. Take a script that runs grep inside a loop over 1,000 files. Refactor to one grep -r or xargs grep.
  2. 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 (time output)
  • No unnecessary forks in hot loops
  • Builtins used where possible
  • Parallelism applied to I/O-bound or CPU-bound independent tasks
  • -print0 / -0 used 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.

Updated: