Home » Linux » Shell » Why You Should Wrap File Paths

Why You Should Wrap File Paths in Strings in Your Shell Scripts

I stumbled across a thread about terrible programming mistakes and found this:

https://github.com/MrMEEE/bumblebee-Old-and-abbandoned/commit/a047be85247755cdbe0acce6f1dafc8beb84f2ac

Which contains the line:

rm -rf /foo-bar-usr /lib/nvidia-current/xorg/xorg

Note – I’ve added foo-bar- to the string so that if you try to run it, it won’t do the thing I’m warning about –even having that on my clipboard makes me nervous!.

What happens when it’s run? It wipes out the entire /usr/ directory – essentially bricking your computer! All because of a single space.

Due to the space after /usr, the rm command interprets it as two separate directories to remove, not one mistyped path.

If that path had been wrapped in quotes so that it was passed as a single parameter, this wouldn’t have happened.

Most command-line examples won’t do this as it can obfuscate the meaning of a script or make it more difficult to read – but if you’re writing scripts rather than executing statements directly on the command line and especially if you’re accepting user input where they might accidentally tap space (never trust users), it’s worth wrapping your file paths as a precaution.

You don’t want to lose data, and you definitely don’t want to lose someone else’s data.

And as always – back up your files and your system regularly! You never know when a mistake like this might slip through – it might not even be your mistake.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment