Check the shebang, permissions, and line endings
A script without a shebang may run under a different shell. Put #!/usr/bin/env bash or #!/bin/sh on line 1 of the script. Use bash features only if the shebang says bash. Make the file executable with chmod 0755 script.sh; keep private scripts at chmod 0700 if others can read the directory. If ./script.sh returns “Permission denied”, check ls -l and fix the mode. If it returns exit code 126, the file is found but not executable; 127 means command not found, often a typo or missing PATH.
Windows line endings produce bad interpreter: /usr/bin/env^M or $'\r': command not found. Convert with sed -i 's/\r$//' script.sh or dos2unix. Run bash -n script.sh to catch syntax errors without executing. This takes seconds and saves hours.
Quote expansions before they split or glob
Unquoted $name is split on spaces and expanded as a filename pattern. rm $file with file="my report.txt" becomes two arguments; file="*.txt" can delete every text file. Use rm -- "$file". Quote command substitutions too: today="$(date +%F)". Double quotes stop splitting and globbing but still allow variable expansion. Single quotes keep text literal.
Remember "$@", not $@, when passing arguments. For a list, use an array in bash: files=("one file.txt" "two.txt") and printf '%s\n' "${files[@]}". If one argument arrives as several, or a filename with spaces is split, suspect quoting first.
Stop unset variables from spreading
A typo in a variable name expands to an empty string, and the script carries on. Put set -u near the top, or set -euo pipefail if you understand the trade-offs, to make unset variables an error. Use default values deliberately: ${HOME:-/tmp} for a fallback, ${1:?usage: script.sh directory} to demand an argument. Do not use set -u and then write $1 without checking; use "$1" after checking $#.
Match the test to the data type
[ "$count" -gt 5 ] compares integers. [ "$name" = "admin" ] compares strings. Mixing them gives errors such as integer expression expected. In bash, prefer [[ ... ]] for pattern matching and safer parsing: [[ $answer == y ]], [[ $path == *.log ]]. Use -eq, -ne, -lt, -le, -gt, -ge for numbers, and =, !=, <, > inside [[ ]] for strings. Use -z for empty and -n for non-empty. Test one condition at a time when learning; complex && and || chains hide mistakes.
Check exit codes and handle failures
Every command returns an exit status: 0 means success, 1 to 125 are command-specific failures. A script that ignores them deletes or reports the wrong thing. Use if ! cp "$src" "$dest"; then echo "copy failed" >&2; exit 1; fi. Put error messages on standard error with >&2. Use set -o pipefail so cmd1 | cmd2 fails when cmd1 fails, not only when the last command fails.
Beginners often assume set -e catches every failure. It does not: commands in if, while, &&, ||, and pipelines behave differently. For anything destructive, check explicitly. Keep logs with timestamps: printf '%s %s\n' "$(date -Is)" "starting backup" >> "$log". If a command may hang, set a timeout, for example timeout 30s command.
Read files with while IFS= read -r
for line in $(cat file.txt) breaks on spaces and runs the loop once per word. Use:
while IFS= read -r line; do printf '%s\n' "$line"; done < file.txt
IFS= preserves leading and trailing whitespace; -r stops backslash interpretation. For files without a final newline, use while IFS= read -r line || [ -n "$line" ]. To process filenames safely, use find . -name '*.log' -print0 | while IFS= read -r -d '' file; do ...; done. Test with a filename containing a space and a newline before trusting the loop with real data.
Make paths explicit and protect destructive commands
Scripts run from cron, another directory, or a desktop shortcut do not share your current directory. Use an explicit base directory: base="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" then "$base/data/input.csv". Avoid cd without checking: cd "$dir" || exit 1.
Before rm -rf, print the target and require a non-empty variable: : "${target:?target is empty}"; printf 'Removing %s\n' "$target"; rm -rf -- "$target". Prefer moving to a temporary directory over permanent deletion, and keep backups for at least 24 hours when testing. Use mv -- "$file" "$file.bak" before rewriting a file. A single missing slash can turn a safe relative path into a broad match.
Diagnose a script that works by hand but fails on a schedule
Symptoms: the script runs when you type it but does nothing under cron, or logs command not found. Likely causes: cron starts with a minimal PATH, a different working directory, no interactive aliases, and a different shell. The fix: use absolute paths for commands and files, set PATH=/usr/local/bin:/usr/bin:/bin at the top, cd to an explicit directory, and redirect both output streams to a log: >> /tmp/script.log 2>&1. Check the log after one run, not after a week. If the script works under bash but not sh, confirm the shebang and avoid bash-only syntax such as arrays or [[ ]] in a #!/bin/sh script.
FAQ
Why does my script say “Permission denied” when I run it?
The file is not executable, or you are running it without the right path. Run chmod 0755 script.sh, then ./script.sh. If you run script.sh without ./, the shell searches PATH and may find nothing or a different file.
Why does my variable disappear inside a loop or pipeline?
In bash, each side of a pipeline can run in a subshell. cat file | while read -r line; do count=$((count+1)); done leaves count unchanged outside the loop. Use input redirection: while IFS= read -r line; do ...; done < file, or use process substitution if available. Also check that you did not use local outside a function or overwrite the variable name.
Is set -e enough to make a script safe?
No. It helps with simple unguarded commands, but it does not cover commands in conditions, pipelines without pipefail, or failures you need to handle yourself. Add set -u and set -o pipefail, check critical commands explicitly, and test with a deliberately missing file before using the script on real data.