How to Recursively Delete Files Using rm -rf and a Variable

If I can delete files with rm -rf local_directory/*, it should be rm -rf "${LOCAL_DIRECTORY}/*" if I store the directory name in a variable, right? It turns out that's not it! 🙈

1 min read
How to Recursively Delete Files Using rm -rf and a Variable
Photo by Ron Lach on Pexels.

I recently created a bash script to periodically backup my databases to Git and I ran into a problem with a single line:

rm -rf "${LOCAL_DIRECTORY:?}/*"

The previous command should have deleted all files located inside the LOCAL_DIRECTORY folder, but it didn't... 🤔

I scratched my head for a long time until I came across this answer on Stack Overflow. I still don't know why, but just putting /* outside the double-quotes solved my problem. 🤩

rm -rf "${LOCAL_DIRECTORY:?}"/*

It's crazy when just three characters completely change the outcome, right? 😅