Loop over array, preventing wildcard expansion (*)

核能气质少年 提交于 2019-11-27 07:03:32

问题


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?


回答1:


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.




回答2:


You can use array to store them:

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

for i in "${array[@]}"
do
    echo "$i"
done


来源:https://stackoverflow.com/questions/13252329/loop-over-array-preventing-wildcard-expansion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!