Alex
Alex

Reputation: 3855

How to evaluate a string variable as a glob pattern?

Let's say I have a list of files and dirs, all in the same directory:

files=(file1 file2 file3 dir1 dir2)
src="path/to/src"

I try to build a glob pattern by joining them into a string by comma:

files_by_comma=$(IFS=, ; echo "${files[*]}")

However, when I try to copy

cp -R "$src/{$files_by_comma}" path/to/dest

I get cp: cannot stat 'path/to/src/{file1,file2,file3,dir1,dir2}': No such file or directory. Of course if I spell out the glob by hand it works just fine:

cp -R /path/to/src/{file1,file2,file3,dir1,dir2} path/to/dest

I tried many variations like cp -R "$src"/{"$files_by_comma"} path/to/dest but it seems the issue is that I'm injecting a string into a glob expression, and it can't evaluate it.

Is it possible to combine a string with a glob in this case? Thanks

Upvotes: 1

Views: 320

Answers (1)

anubhava
anubhava

Reputation: 786241

You don't need to build a string with comma as you already have file names in an array. You just need to use:

files=(file1 file2 file3 dir1 dir2)
src="path/to/src"

cp -R "${files[@]/#/$src/}" path/to/dest

Upvotes: 1

Related Questions