我基本上took this bash recipe根据有无参数调用package.json
脚本来运行不同的命令...
"scripts": {
"paramtest": "if [ -z $1 ]; then echo \"var is unset\"; else echo \"var is set to {$1}\"; fi",
...
不带参数的调用可以按预期进行:
$>yarn paramtest
var is unset
$>npm run paramtest
var is unset
$>
使用参数调用会给我一个错误:
$>yarn run paramtest foo
/bin/sh: 1: Syntax error: word unexpected
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
$>npm run paramtest -- foo
> photocmd@0.0.7 paramtest /depot/own/photocmd
sh: 1: Syntax error: word unexpected
...
答案 0 :(得分:0)
根据this答案和this注释,yarn run
仅支持将参数传递到脚本的末尾,而不是中间。此行为类似于npm run
。
要避免此限制,您需要将当前的条件逻辑放在bash function的正文中。例如:
"scripts": {
"paramtest": "func () { if [ -z \"$1\" ]; then echo \"var is unset\"; else echo \"var is set to ${1}\"; fi ;}; func",
...
现在,当您通过CLI将参数传递给脚本时,它将得到:
paramtest
脚本的末尾,即在func
调用之后。func
函数本身。func
函数的主体中,在测试中使用$1
并在${1}
字符串中使用echo
来引用第一个参数。 注意:测试中的$1
用json转义的双引号引起来,即\"$1\"
运行脚本:
通过CLI将参数传递给脚本时,在脚本名称(即--
)和参数(paramtest
)之间也包含foo
会更安全。例如:
yarn run paramtest -- foo
^^
因为您的参数以连字符开头(如以下命令所示),它将被解释为一个选项:
yarn run paramtest -foo
^
,您的脚本将打印:
var is unset
但是,如下例所示添加--
;
yarn run paramtest -- -foo
^^ ^
正确打印:
var is set to -foo