Work the Shell - Dealing with Spaces in Filenames
and reversed with:
original="$(echo $safename | sed s'/_-_/ /g')"
It solves the problem, but it's definitely not a very efficient or smart use of computing resources.
I've outlined three possible solution paths herein: modifying the IFS value, ensuring that you always quote filenames where referenced, and rewriting filenames internally to replace spaces with unlikely character sequences, reversing it on your way out of the script.
By the way, have you ever tried using the find|xargs pair with filenames that have spaces? It's sufficiently complicated that modern versions of these two commands have special arguments to denote that spaces might appear as part of the filenames: find -print and xargs -0 (and typically, they're not the same flags, but that's another story).
During the years I've been writing this column, I've more than once tripped up on this particular problem and received e-mail messages from readers sharing how a sample script tosses up its bits when a file with a space in its name appears. They're right.
My defensive reaction is “dude, don't use spaces in filenames”, but that's not really a good long-term solution, is it?
What I'd like to do instead is open this up for discussion on the Linux Journal discussion boards: how do you solve this problem within your scripts? Or, do you just religiously avoid using spaces in your filenames?
Dave Taylor has been hacking shell scripts for a really long time, 30 years. He's the author of the popular Wicked Cool Shell Scripts and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Win an iPhone 6
Enter to Win
|Geek Hide-away in Guatemala - Stay for Free!||Nov 26, 2015|
|Microsoft and Linux: True Romance or Toxic Love?||Nov 25, 2015|
|Non-Linux FOSS: Install Windows? Yeah, Open Source Can Do That.||Nov 24, 2015|
|Cipher Security: How to harden TLS and SSH||Nov 23, 2015|
|Web Stores Held Hostage||Nov 19, 2015|
|diff -u: What's New in Kernel Development||Nov 17, 2015|
- Cipher Security: How to harden TLS and SSH
- Microsoft and Linux: True Romance or Toxic Love?
- Non-Linux FOSS: Install Windows? Yeah, Open Source Can Do That.
- Geek Hide-away in Guatemala - Stay for Free!
- Firefox's New Feature for Tighter Security
- Web Stores Held Hostage
- It's a Bird. It's Another Bird!
- PuppetLabs Introduces Application Orchestration
- diff -u: What's New in Kernel Development
- IBM LinuxONE Provides New Options for Linux Deployment