[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

How to handle passing filenames with spaces and wildcards into bash scripts?



Greetings all,

I have done a fair amount of experimentation and Googling trying to find an answer to this and was wondering if some of the bash-scripting gurus out there could give me a hand.

I am trying to make a script that will accept a wildcard to match a bunch of files and iterate over those absolute filenames; running the command once per filename. It is fairly straight-forward to do so when the filesnames don't have spaces but I haven't been able to find the magic combination that doesn't treat every space as a list separator.
The closest I have gotten is to use the following script:

#!/bin/bash
find $* -print0 | xargs -0 -I % command_to_iterate_over %

If I type:
script "./path/to/filename*"
it seems to iterate over the list properly whether there are spaces in there or not.

If I type:
script "./path/to/filename\ with\ spaces*"
or
script "./path/to/filename with spaces*"
find chops up the filename at each space and tries to find each part which fails.

If I put quotes around the $*
find says that it cannot find ./path/to/filename\ with\ spaces*

If I replace "find $*" with "find . -name $*" that doesn't help since it will start in the current directory (I want paths to be absolute) and won't match since the path is not stripped out of $* and $* could have multiple arguments.

I have failed in similar ways using both while and for loops too.

What am I missing here ... is there a better command than find to expand my wildcard and pass them to xargs? You seem to need the null separator between the filenames. Am I going to have to do some manual regex string parsing (after learning how to do so) to preprocess the command line arguments? I could probably do some crazy stuff with find, sed and grep ... I am just checking if there is something obvious/standard that I am missing.

Does anyone have some bash magic for me that expands the wildcard and bundles each filename in quotes to pass on to a command one at a time in a simple manner?

Thanks in advance for any hints/help/pointers/tricks that you can provide.
/Mike

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]