bash - 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"
但是现在该命令错过了双破折号参数。
解决方案
考虑消除“脚本”中间变量
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 "$@"
推荐阅读
- php - 如何给输入“提交”类型一个文本值以及一个 PHP id 以通过 POST 请求来识别该值以删除数据库条目?
- reactjs - updateLastConsumedMessageIndex 冻结导致消息中没有更新
- python - 您可以将 API 调用直接拉入 Pandas Dataframe 吗?
- php-openssl - openssl_seal 失败错误:0E06D06C:配置文件例程:NCONF_get_string:无值
- java - 收到 Kafka 消息后 10 分钟内安排事件
- angular - 带有来自 API 的动态数据的 Angular highchart
- javascript - jQuery无法获取按钮旁边的textarea
- python - 在时间序列中编辑密集的 x 标签
- ruby - 如何存根返回集合 rspec 的方法
- c# - Selenium 截图到内存