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.
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems
Join editor Bill Childers and Bit9's Paul Riegle on April 27 at 12pm Central to learn how to keep your Linux systems secure.
Free to Linux Journal readers.Register Now!
|diff -u: What's New in Kernel Development||Aug 20, 2014|
|Security Hardening with Ansible||Aug 18, 2014|
|Monitoring Android Traffic with Wireshark||Aug 14, 2014|
|IndieBox: for Gamers Who Miss Boxes!||Aug 13, 2014|
|Non-Linux FOSS: a Virtualized Cisco Infrastructure?||Aug 11, 2014|
|Linux Security Threats on the Rise||Aug 08, 2014|
- diff -u: What's New in Kernel Development
- Security Hardening with Ansible
- NSA: Linux Journal is an "extremist forum" and its readers get flagged for extra surveillance
- Monitoring Android Traffic with Wireshark
- Tech Tip: Really Simple HTTP Server with Python
- Readers' Choice Awards 2013
- RSS Feeds
- [<Megashare>] Watch Mrs Brown's Boys Movie Online Full Movie HD 2014
- Cooking with Linux - Serious Cool, Sysadmin Style!
- Senior Perl Developer