SC2115: the empty variable that turns rm -rf

SC2115: the empty variable that turns rm -rf "$DIR/"* into rm -rf /*

●2 ●40 ●103
calendar_today • schedule1 min read

rm -rf "$TARGET/"* looks correct. The quotes are right and the glob sits outside them, where it has to. I put it in a two-line script in a scratch directory and asked what happens when TARGET is empty, with echo in front so rm never ran: the command line came back as rm -rf /backup /bin /boot /dev /etc /home ..., every top-level directory on the machine.

set -u does not catch it, because an empty string is set. A ${1:-} default or a blank config line passes strict mode, and set -e stays quiet because rm succeeds. ShellCheck 0.11.0 flags the line as SC2115, and the fix is in the warning's text:

$ printf '#!/bin/bash\nrm -rf "${TARGET:?}/"*\n' > t2.sh
$ shellcheck t2.sh; echo "sc rc=$?"
sc rc=0
$ cd tree
$ TARGET= bash ../t2.sh; echo "exit=$?"
../t2.sh: line 2: TARGET: parameter null or not set
exit=1

With TARGET empty the script stopped on line 2 and the scratch tree was untouched; with a real path it emptied exactly that directory. Keep the colon: ${TARGET?} rejects only unset, which is where set -u already left you. And :? does not catch a wrong non-empty value, so check the path sits inside the tree you expect before any rm -rf.

The staging-tree run, and a table of which rm -rf forms trigger the warning, are in the SC2115 deep dive.


I bundled the scripts I copy onto every new server, plus 10 bonus ones, into the Production Bash Toolkit. 30-day refund if it isn't useful.

Want more #devops & #linux deep dives?

Join 6,145+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

The cleanup failed on the night there was nothing to clean

BashSnippets - Dec 2

A deploy guard that passes with no token

BashSnippets - Nov 24

StarlingX 13.0 Turns Two Edge Upgrades Into One Reboot. Test the Targets Yourself.

Tom Smithverified - Nov 24

A Function Without local Overwrote My Variable and rm -rf Deleted the Wrong Directory

BashSnippets - Jun 21

ShellCheck rates SC2086 as info. It let rm delete two files I never named.

BashSnippets - Sep 29
chevron_left
4k Points • 145 Badges
North America • bashsnippets.xyz
79Posts
43Comments
14Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!