将文字通配符存储在 bash 字符串中

Store literal wildcard character in bash string

假设我有一个函数

print_args () {
    for i in $@; do
        echo "$i"
    done
}

当我做的时候

foo='\*'
print_args $foo

我明白了

\*

(带反斜杠)作为输出。

如果我将 foo 的定义更改为 foo='*',则当 运行 print_args $foo.

时,我将获得当前目录中的所有文件

所以我要么包含反斜杠,要么解释 *,但我不知道如何从字面上获取 *

无论是否在 $foo 周围包含双引号,输出都是相同的。

一般规则是引用所有变量。它可以防止 shell 扩展和拆分空格。所以你的函数应该看起来像这样(引用 $@,以及 ${array[@]} 按参数拆分):

print_args () {
    for i in "$@"; do
        echo "$i"
    done
}

并这样称呼它:

print_args "$foo"