Linux Basic — Clean & Readable Code Practice

1 minute read

Practice Exercises — Clean & Readable Code

Refactor existing scripts to make them maintainable.


Warm-up

  1. Take a script with single-letter variable names and rename them to descriptive snake_case names.
  2. Add a header block with description, usage, dependencies, and exit codes.
  3. Extract a repeated 10-line block into a function.

Naming

  1. Convert all environment variables to UPPER_CASE.
  2. Convert all local variables to lowercase_snake_case.
  3. Rename functions to verb-first: userCount() → get_user_count().

Commenting

  1. Find 3 “what” comments and rewrite them as “why” comments.
  2. Add a comment explaining a magic number (e.g., sleep 5).
  3. Remove redundant comments that just restate the code.

Organization

  1. Refactor a monolithic 200-line script into 5–7 functions, each with a single responsibility.
  2. Move all readonly constants to the top.
  3. Add a main() function and move script body into it.

ShellCheck

  1. Run shellcheck on a script and fix all quoting warnings (SC2086, SC2046).
  2. Fix cd usage (SC2164) by adding || exit.
  3. Fix array expansion (SC2128) by using "${arr[@]}".
  4. Achieve zero warnings at default level.

Full Refactor

  1. Take a legacy script with no header, cryptic names, and no functions. Apply all techniques from this chapter to make it production-ready.

Verification Checklist

  • All variables quoted unless splitting is intentional
  • ShellCheck passes with zero warnings
  • Functions are < 50 lines each
  • Script has a complete header
  • main() is at the bottom
  • Constants are readonly and at the top

Next chapter → Optimizing Scripts

Updated: