Postsread more
Error-First Pattern: Writing Self-Documenting Bash
There’s a pattern in shell scripts that makes code harder to read than it needs to be. It looks like this:
if [[ -f "$config_file" ]]; then
if [[ -r "$config_file" ]]; then
source "$config_file"
if [[ -n "$DATABASE_URL" ]]; then
connect_to_database
if [[ $? -eq 0 ]]; then
run_migrations
# ... and so on
else
echo "Connection failed" >&2
exit 1
fi
else
echo "DATABASE_URL not set" >&2
exit 1
fi
else
echo "Config not readable" >&2
exit 1
fi
else
echo "Config not found" >&2
exit 1
fi
You’ve seen this. You’ve probably written this. I haven’t. Sorry, not sorry.