Specialized knowledge of Bash and Zsh scripting, shell automation, command-line tools, and scripting best practices...
Expert guidance for writing robust, maintainable Bash and Zsh scripts with best practices for automation and command-line tool usage.
Start every script with:
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -e: Exit on errorset -u: Error on undefined variablesset -o pipefail: Catch errors in pipesIFS=$'\n\t': Safer word splitting"$variable" not $variable[[ for conditionals (Bash): if [[ "$var" == "value" ]]; thenif command -v git &> /dev/null; thenls: Use globs or find insteadfiles=("file1" "file2") not space-separated stringstrap cleanup EXIT
trap 'echo "Error on line $LINENO"' ERR
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help) usage; exit 0 ;;
-v|--verbose) VERBOSE=true; shift ;;
-*) echo "Unknown option: $1"; exit 1 ;;
*) break ;;
esac
done
# Prefer this (handles spaces, newlines correctly):
while IFS= read -r -d '' file; do
echo "Processing: $file"
done < <(find . -type f -name "*.txt" -print0)
# Or with simple globs:
for file in *.txt; do
[[ -e "$file" ]] || continue # Skip if no matches
echo "Processing: $file"
done
read -rp "Continue? [y/N] " response
if [[ "$response" =~ ^[Yy]$ ]]; then
echo "Continuing..."
fi
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}Success${NC}"
echo -e "${RED}Error${NC}" >&2
When appropriate, suggest these modern replacements:
ripgrep (rg) β faster than grepfd β faster than findfzf β interactive filteringjq β JSON processingyq β YAML processingbat β cat with syntax highlightingeza β enhanced lsusage() {
cat <<EOF
Usage: ${0##*/} [OPTIONS] <args>
Description of what this script does.
OPTIONS:
-h, --help Show this help
-v, --verbose Verbose output
EOF
}
main() {
# Main logic here
:
}
When user specifies Zsh:
**/*.txt (recursive), *.txt~*test* (exclude pattern)${var:u} (uppercase), ${var:l} (lowercase)typeset -A hash; hash[key]=valuesetopt extended_globeval untrusted inputmktemp for temporary files: TEMP_FILE=$(mktemp)rm -rf operations[[ ]] vs test, $(( )) vs expr)var=$(cat file) β var=$(<file)read not cat | while: while read -r line; do ... done < filexargs -P or GNU parallel for parallel processingSee references/template.sh for a complete, production-ready script template with all best practices incorporated.