纱/ npm:根据设定变量执行

时间:2018-10-10 09:27:15

标签: bash npm yarnpkg

我基本上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
...

怎么了?

1 个答案:

答案 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将参数传递给脚本时,它将得到:

  1. 添加到paramtest脚本的末尾,即在func调用之后。
  2. 随后作为参数传递给func函数本身。
  3. 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