首页 > 解决方案 > Shell 脚本 - 在参数中间保留双引号,而不使用 \ 转义

问题描述

我正在编写一个 shell 脚本来帮助我运行 react-native 项目,我的脚本有以下部分:

#some steps to create $calculated_value...

os_type=$1
shift
script="$calculated_value react-native run-$os_type $@"
$script

当我在终端中键入此命令时:

./scripts/run ios --simulator="iPhone 6"

我希望脚本最后应该执行以下命令:

"$calculated_value" react-native run-ios --simulator="iPhone 6"

但是,脚本现在执行此命令:

"$calculated_value" react-native run-ios --simulator=iPhone 6

双引号消失了,终端只是读取了没有“6”的模拟器。

我试过用替换$@$(for i;do echo ${i@Q};done;)
但它给了我错误:line 25: ${i@Q}: bad substitution

我知道我可以\在双引号之前添加以对其进行转义,
但只是想看看是否有任何解决方案可以跳过添加\.

---------------------------------------------- 编辑信息 -- ------------------------------------------

现在我eval在脚本内部使用,以便使用文件位置运行命令。
在脚本内部,它包含以下步骤:

...some calculation to get $envfile

os_type=$1
shift

run_script="ENVFILE=$envfile react-native run-$os_type $@"
eval $run_script

在我的里面package.json

{
  "scripts": {
    "dev": "./scripts/dev"
  }
}

在我的真实情况下,当我输入:

npm run dev ios -- --simulator="iPhone 6"  

我的预期是:

ENVFILE=env/tw.dev react-native run-ios --simulator="iPhone 6"

但是现在该命令错过了双破折号参数。

标签: bashshellsh

解决方案


考虑消除“脚本”中间变量

os_type=$1
shift
"$calculated_value" react-native "run-$os_type" "$@"

'run-$os_type' 和 '$@' 周围的引号将使用空格(或其他“神奇”字符:*、?、...)解决参数的正确扩展。

目前尚不清楚“$calculated_value”的值是什么,答案假设它是程序的路径(没有额外的参数)。如果它可能包含参数或选项,您可能必须远程引用它周围的引号。

编辑 2019-10-10:

使用原始代码(“script=... $@”),bash 会将输入参数('$@')分解为赋值命令中的标记。阻止此步骤的可能替代方法是:

script="$calculated_value" react-native "run-$os_type"
$script "$@"

推荐阅读