What I do
Provide comprehensive guidelines for writing maintainable and robust shell scripts, including:
- Use bash with proper error handling options
- Modern syntax and best practices
- Debugging support
- Help functionality
- A standard script template
When to use me
Use this skill when you need to write, review, or improve shell scripts. It covers best practices for bash scripting to ensure scripts are reliable, debuggable, and maintainable.
Best Practices
-
Use bash: Stick to bash for portability and collaboration. Avoid zsh, fish, or other shells unless absolutely necessary.
-
Shebang: Always start with
#!/usr/bin/env bash, even if not making the script executable. -
File extension: Use
.shor.bashextension for clarity. -
Error handling:
set -o errexit: Exit on command failureset -o nounset: Fail on unset variables (use"${VARNAME-}"for optional variables)set -o pipefail: Treat pipeline failures as errors
-
Debugging: Use
set -o xtraceconditionally:if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace; fito enable withTRACE=1 ./script.sh -
Conditions: Use
[[ ]]instead of[ ]ortestfor better functionality. -
Variable quoting: Always quote variable accesses with double quotes:
"$VAR". Exception: left-hand side of[[ ]]conditions. -
Functions: Use
localfor function variables. -
Help handling: Check for help flags like
-h,--help,help,h,-helpand print usage. -
Error output: Redirect errors to stderr:
echo 'Error message' >&2 -
Options: Prefer long options like
--silentover-sfor clarity. -
Working directory: Change to script directory:
cd "$(dirname "$0")" -
Linting: Use shellcheck and heed its warnings.
Template
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
echo 'Usage: ./script.sh arg-one arg-two
This is an awesome bash script to make your life better.
'
exit
fi
cd "$(dirname "$0")"
main() {
echo do awesome stuff
}
main "$@"
Follow these practices to write maintainable, robust shell scripts.