[Gllug] shell quoting problem

ccooke ccooke-gllug at gkhs.net
Wed Jul 2 11:39:23 UTC 2008


On Wed, Jul 02, 2008 at 10:47:13AM +0100, Alain Williams wrote:
> A little problem that is rearing its head more and more since some of my clients
> insist on creating files with spaces in the names. An example that happened just
> now:
> 
> I wanted to find files that had 'John Smith' as part of the name and 'ls' them.
> 
> 	ls -l $(locate 'John Smith')
> Doesn't work since the spaces are interpretted as argument separators - as I expected.
> 
> 	ls -l "$(locate 'John Smith')"
> Doesn't work since ls looks for a big long file name with embedded \n in it.

<snip>

locate -0 "John Smith" | xargs -0 ls -l

if you need to do something programmatical with the results (more than
pass them to an external program), try this:

function grabfiles
{
	local search="$1"
	local IFS=$'\n'
	FILES=( $( locate "$search" ) )
}

... and subsequently you'll have an array, FILES, containing one file
per entry. You can use that safely with any shell command by
double-quoting with an index of '@': "${FILES[@]}". This will expand to
each entry in the array, individually quoted. Remember to double-quote
any variable that might have a space in it (or just 'every variable',
for good practice') and it'll all work.

-- 
Charles Cooke, Sysadmin 
Say it with flowers, send a triffid.
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list