Defensive File Operations
Dry Run File Action
Preview or Apply
A dry-run flag lets a script show the intended file action before applying it. The same target can produce a preview or an apply plan.
Program
Play the script to choose dry-run mode and see the file action plan.
dry_run_file_action.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
dry_run=1
path="build/tmp"
if [ "$dry_run" -eq 1 ]; then
action="would remove $path"
else
action="remove $path"
fi
echo "$action"
#!/usr/bin/env bash
dry_run=0
path="build/tmp"
if [ "$dry_run" -eq 1 ]; then
action="would remove $path"
else
action="remove $path"
fi
echo "$action"
dry_run ← 1
3dry_run=14path="build/tmp"values this step1dry_runpath ← build/tmp
3dry_run=14path="build/tmp"5if [ "$dry_run" -eq 1 ]; thenvalues this stepbuild/tmppathif [ "$dry_run" -eq 1 ]; then
4path="build/tmp"5if [ "$dry_run" -eq 1 ]; then6 action="would remove $path"values this step1dry_runaction ← would remove build/tmp
5if [ "$dry_run" -eq 1 ]; then6 action="would remove $path"7elsevalues this stepwould remove build/tmpactionbuild/tmppathecho "$action"
9fi10echo "$action"outputwould remove build/tmpvalues this stepwould remove build/tmpaction
dry_run ← 0
3dry_run=04path="build/tmp"values this step0dry_runpath ← build/tmp
3dry_run=04path="build/tmp"5if [ "$dry_run" -eq 1 ]; thenvalues this stepbuild/tmppathif [ "$dry_run" -eq 1 ]; then
4path="build/tmp"5if [ "$dry_run" -eq 1 ]; then6 action="would remove $path"values this step0dry_runaction ← remove build/tmp
7else8 action="remove $path"9fivalues this stepremove build/tmpactionbuild/tmppathecho "$action"
9fi10echo "$action"outputremove build/tmpvalues this stepremove build/tmpaction
dry run
A dry run previews the action without applying it.
apply mode
Apply mode should be explicit and visible.
file action
Destructive file actions are safer when the exact path is displayed first.