遍历数组,防止通配符扩展(*) [英] Loop over array, preventing wildcard expansion (*)
问题描述
我试图弄清我认为BASH中的一个小问题,但是我很难找到正确的语法.我想遍历一组值,其中一个是星号(*),我不希望在此过程中发生任何通配符扩展.
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
代替上面的内容,我在当前目录中得到一个目录列表,然后是* .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:
推荐答案
您的问题是您需要一个数组,但是您编写了一个包含元素的单个字符串,这些元素之间有空格.请改用数组.
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')
始终在变量替换处使用双引号(即"$foo"
),否则shell将变量的值拆分为单独的单词并将每个单词视为文件名通配符模式.命令替换也是如此:"$(somecommand)"
.对于数组变量,使用"${array[@]}"
展开到数组元素的列表.
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
有关更多信息,请参见关于数组的bash常见问题解答.
For more information, see the bash FAQ about arrays.
这篇关于遍历数组,防止通配符扩展(*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!