You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash 4.2中通过变量向函数传递带引号的参数

问题原因

当执行myfunc $myvar时,Bash会先展开变量得到foo bar "blah blah",随后进行单词拆分——仅按空白字符(空格、制表符、换行)分割内容,字符串里的双引号会被当成普通字符处理,不会被解析为参数边界,最终函数收到4个参数:foo、bar、"blah、blah"。

针对Bash 4.2的解决方案

以下几种方法都能让第二次调用和第一次效果一致:

方法1:使用eval(需确保变量内容安全)

eval会重新解析变量展开后的字符串,把双引号当成语法的一部分处理,正确拆分参数:

myfunc() {
  for myarg in "${@}"
  do
    echo ">>$myarg<"
  done
}

echo "prints three things"
myfunc foo bar "blah blah"

echo "now this prints three too"
myvar="foo bar \"blah blah\""
eval myfunc $myvar

注意:如果myvar内容来自不可信来源,eval可能执行恶意命令,仅在内容可控时使用。

方法2:使用xargs拆分参数

xargs会自动识别字符串中的引号,将带引号的内容作为单个参数传递:

myfunc() {
  for myarg in "${@}"
  do
    echo ">>$myarg<"
  done
}

echo "prints three things"
myfunc foo bar "blah blah"

echo "now this prints three too"
myvar="foo bar \"blah blah\""
echo "$myvar" | xargs myfunc

方法3:用read -a将字符串读入数组

Bash 4.2支持read -a选项,可将带引号的字符串解析为数组元素,再传递数组给函数:

myfunc() {
  for myarg in "${@}"
  do
    echo ">>$myarg<"
  done
}

echo "prints three things"
myfunc foo bar "blah blah"

echo "now this prints three too"
myvar="foo bar \"blah blah\""
read -r -a myarr <<< "$myvar"
myfunc "${myarr[@]}"

内容的提问来源于stack exchange,提问作者swdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:15:36