Knowledgebase

Writing Safe Shell Scripts Print

  • programminglanguages, programming, permissions, guide, howto, solution, zillionkinghost, hosting
  • 0

Avoiding damage.

WHAT SHELL SCRIPTS FREQUENTLY DO

Delete files, change permissions, restart services, and modify configuration.

WHY THAT MATTERS

A fault does real damage, immediately and irreversibly.

WHAT TO ALWAYS DO

Quote every variable Check that variables are set before using them Verify a path before operating on it Use absolute paths, or set the directory explicitly

WHAT THE CLASSIC DISASTER IS

A deletion where a variable was empty, so the path became the root.

WHAT PREVENTS IT

Checking the variable is non-empty before use.

WHAT TO ADD

A dry-run mode, printing what would be done.

WHY

It allows verification before anything is changed.

WHAT TO LOG

What the script did, with timestamps.

WHAT TO HANDLE

Being run twice, so it is safe to repeat.

WHAT TO AVOID

Parsing output of commands whose format may change Assuming commands exist without checking Running as an administrative user unnecessarily

WHAT TO TEST

Every path, including failure paths.

WHAT TO REVIEW

Any script that runs automatically and unattended.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot