Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...