A shell script is only as safe as the checks you run before it touches real files. Use this list in order: define the job, lock down the shell, quote inputs, test on copies, then run once with a way back.
1. Write the job in one sentence and set a size limit
- State the input, the action, and the single output in one sentence. Example: "Read a folder of
.txtfiles and write oneindex.txtfile." - Limit the first version to 50 lines or fewer. If it needs more, remove a feature.
- Name one success condition you can check in under 5 seconds, such as "the output file exists and has at least 1 line."
- List every input path before coding. If there are more than 3 inputs, use a configuration file or split the script.
- Put the script in its own folder. Keep test data in a separate
test-datafolder.
2. Declare the shell and open with safety settings
- Use exactly one shebang on line 1:
#!/usr/bin/env bashfor Bash, or#!/bin/shfor POSIX shell. Do not mix Bash-only syntax into ashscript. - For Bash, start with
set -euo pipefail. For plainsh, useset -euand check pipelines separately. - Add a two-line header: one line for purpose, one line for required shell. Include a version number such as
v0.1. - Use 2 spaces or 4 spaces for indentation and keep it consistent; inconsistent indentation hides missing
thenandfilines. - Run a syntax check before the first execute:
bash -n script.shorsh -n script.sh.
3. Make quoting and argument checks a fixed habit
- Quote every variable expansion:
"$file","$1","$HOME". Unquoted paths break at the first space. - Set a default for optional values:
${1:-default}. Withset -u, an unset variable stops the script. - Check the argument count at the top. If the script needs 2 arguments, exit with status
2when$#is less than 2. - Use
printf '%s\n' "$value"rather thanechowhen the value may contain backslashes or leading dashes. - Do not parse the output of
ls. Use a shell glob such asfor file in ./*.txt, orfind ... -print0withwhile IFS= read -r -d '' file.
4. Add safety rails before any write or delete
- Run the script as a normal user, not with
sudo. Tests with elevated permission hide ownership mistakes. - Set
umask 077when the script creates private files. Usechmod 700 script.shfor a private script orchmod 755 script.shfor one other users may run. - Print the target path and ask for confirmation before
rm,mv, or overwrite. A simpleread -r answerwith a requiredyesis enough. - Back up any file you overwrite. Keep 3 copies and delete backups older than 7 days if the script runs on a schedule.
- Put temporary files under one directory and remove them with
trap 'rm -rf "$tmpdir"' EXIT. - Set a 10-second timeout on network calls; if the script has no network step, skip this and keep the first version local-only.
5. Check exit codes, error messages, and logs
- Exit
0on success. Use1to125for expected failures you define;126,127, and128-plus have shell meanings, so do not reuse them for your own errors. - Check every command that matters:
if ! cp "$src" "$dst"; then printf 'copy failed\n' >&2; exit 1; fi. - Send error text to stderr with
>&2; send normal output to stdout. - Keep one log file per run, capped at 10 MB. If logs are long-lived, keep 7 daily files and delete older ones.
- Print one progress line per 100 files processed, or per 30 seconds, so a hung script is visible.
6. Test the smallest useful matrix
- Test with 0 arguments, 1 argument, and 2 arguments. Each should produce a clear message or a valid result.
- Use a temporary test folder containing 3 files: one normal name, one with a space, one empty. Total test data should stay under 1 MB.
- Run the script twice in a row. The second run should not duplicate output or fail because the output already exists.
- Test one failure path by making an input unreadable with
chmod 000 file; restore it withchmod 644 fileafter the test. - Time the run. If it takes more than 30 seconds on 100 files, reduce scope before adding features.
7. Diagnose the most common first-script failure
Symptoms: running ./script.sh prints Permission denied, command not found, or the script stops after one line with no message.
Likely causes: the execute bit is missing; the shebang is missing or wrong; the file has CRLF line endings; a command is not installed; set -e stopped the script on an unchecked command; or a variable was empty and the path collapsed.
The fix: check the first 3 lines with head -3 script.sh, confirm the shebang is line 1, run bash -n script.sh, then chmod 700 script.sh for private use or chmod 755 script.sh for shared use. Convert CRLF line endings in your editor if \r appears at line ends. Run bash -x script.sh to see each command, and quote every path. If the error is command not found, check the command name and whether it is available in your PATH; do not install random tools just to make the error disappear.
8. Do the final pre-run check
- Confirm the current directory with
pwdand list the exact target withls -ld. - Make a copy of any real data before the first run; keep the copy at least until the second successful run.
- Check that no password, token, or private key is written in the script; read secrets from environment variables at run time.
- Confirm the script is 50 lines or fewer, has a syntax check, and has one tested output path.
- Run the script once by hand. Only after that add a schedule, and start with a 15-minute interval rather than every minute.
FAQ
What should line 1 of a shell script be?
A shebang: #!/usr/bin/env bash or #!/bin/sh. It must be the first line, with no blank line above.
How long should a beginner shell script be?
Aim for 50 lines or fewer. If you pass 100 lines, split the work into functions or separate scripts.
How do I know a shell script is safe to run?
It is safe enough when it has run on a copy, prints its targets, checks exit codes, and has a backup you have restored once. If it deletes or moves real data, test that path separately before scheduling it.