Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over array, preventing wildcard expansion (*)

I'm trying to figure out what I thought would be a trivial issue in BASH, but I'm having difficulty finding the correct syntax. I want to loop over an array of values, one of them being an asterisk (*), I do not wish to have any wildcard expansion happening during the process.

 WHITELIST_DOMAINS="* *.foo.com *.bar.com"
 for domain in $WHITELIST_DOMAINS
 do
    echo "$domain"
 done

I have the above, and I'm trying to get the following output:

 *
 *.foo.com
 *.bar.com

Instead of the above, I get a directory listing on the current directory, followed by *.foo.com and *.bar.com

I know I need some escaping or quoting somewhere.. the early morning haze is still thick on my brain.

I've reviewed these questions:

How to escape wildcard expansion in a variable in bash?

Stop shell wildcard character expansion?

like image 973
Tal Avatar asked Nov 06 '12 13:11

Tal


2 Answers

Your problem is that you want an array, but you wrote a single string that contains the elements with spaces between them. Use an array instead.

WHITELIST_DOMAINS=('*' '*.foo.com' '*.bar.com')

Always use double quotes around variable substitutions (i.e. "$foo"), otherwise the shell splits the the value of the variable into separate words and treats each word as a filename wildcard pattern. The same goes for command substitution: "$(somecommand)". For an array variable, use "${array[@]}" to expand to the list of the elements of the array.

for domain in "${WHITELIST_DOMAINS[@]}"
 do
    echo "$domain"
 done

For more information, see the bash FAQ about arrays.

like image 59
Gilles 'SO- stop being evil' Avatar answered Nov 12 '22 05:11

Gilles 'SO- stop being evil'


You can use array to store them:

array=('*' '*.foo.com' '*.bar.com')

for i in "${array[@]}"
do
    echo "$i"
done
like image 28
kev Avatar answered Nov 12 '22 07:11

kev