如果我在 bash 中使用函数,则出现单引号问题

single quote issue if i use function in bash

我有如下脚本,我在 mongodb 中 运行 查询。但是当我将它作为函数调用时,它会添加单引号并且我的查询不起作用。我该如何解决这个问题?

我的代码:

mongo_func() {
        mongo "$MONGO/" --quiet --eval   
}

mongo_func "Users" 'db.ucol.updateMany({}, { $unset : {"name" : "", "Users": ""}});'

当我使用 bash -x 进行调试时,输出如下所示。

mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({},' '{$unset:' '{"name"' : '"",' '"Users":' '""}});'

正常运行如下

mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({}, {$unset: {"name" : "", "Users": ""}});'

那是因为你没有引用函数参数。

试试这个。

mongo_func() {
    user=
    shift
    mongo "$MONGO/$user" --quiet --eval "$@"
}