how to use a string as an argument in an for … in … statement in linux shell

I'm familiar with the structure of

for file in foo/folder\ with\ spaces/foo2/*.txt
do
    #do some stuff...
done

However, I want to put foo/folder with spaces/foo2/*.txt into a variable and then use it. Something like this:

myDirectory="foo/folder with spaces/foo2/*.txt"

for file in $myDirectory
do
    # do some stuff
done

But what I've written here doesn't work, and it won't work even if I do

myDirectory="food/folder\ with\ spaces/foo2/*.txt"

or

for file in "$myDirectory" ...

Any help? is this even possible?

Answers


Try using the ls command in the for loop. This works for me:

for file in `ls "$myDirectory"`

don't parse ls

# your files are expanded here
# note lack of backslashes and location of quotes
myfiles=("food/folder with spaces/foo2/"*.txt)

# iterate over the array with this
for file in "${myfiles[@]}"; do ...

Parsing ls is a bad idea, instead just do the shell globbing outside of the quotes.

You could also do:

$mydir="folder/with spaces"

for file in "$mydir"/*; do
  ...
done

Also look into how find and xargs works. Many of these sort of problems can be solved using those. Look at the -print0 and -0 options in particular if you want to be safe.


Need Your Help

How to implement design time validations for XAML, that result in compile errors?

.net wpf data-binding xaml expression

How to enforce that developers writing XAML in Visual Studio should follow certain standards and validations need to be run and if invalid compile time errors are thrown.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.