代码之家  ›  专栏  ›  技术社区  ›  Frank N dqthe

npm运行脚本中参数的if else

  •  2
  • Frank N dqthe  · 技术社区  · 6 年前

    我想调用其他不同的脚本,这取决于是否给定了参数:

    "paramtest": "if [ -z $1 ]; then echo Foo $1; else echo Bar; fi",
    

    应该给“吧”。

    npm运行参数测试——不管怎样

    应该给“Foo whatever”。

    (参数被添加到整行,而不是“传入”)

    > if [ -z $1 ]; then echo Foo; else echo Bar; fi "whatever
      sh: 1: Syntax error: word unexpected
    

    我能做得更好吗?

    基本上,我是在用相同的命令运行完整的测试套件/只运行单个测试之后。。。

    "test" : "if [ -z $1 ]; then mocha ./test/**/*.test.js; else mocha $1
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Josh Brobst    4 年前

    将其包装到shell函数中应该可以做到以下几点:

    "test": "f() { if [ $# -eq 0 ]; then mocha './test/**/*.test.js'; else mocha -- \"$@\"; fi; }; f"
    

    注意,我稍微更改了if条件和else分支,以便在必要时可以指定多个文件参数。

    更简洁的方法:

    "test": "f() { mocha -- \"${@:-./test/**/*.test.js}\"; }; f"
    

    git aliases .


    详细说明

    "scripts": {
        "myscript": "if [ \"$1\" = one ]; then printf %s\\\\n \"$@\"; else echo false; fi"
    }
    

    这里,如果第一个参数是“one”,则打印所有参数,否则打印“false”。我们当然是假设 npm run-script 正在使用类似sh的shell,而不是,例如,Windows的cmd.exe。

    npm documentation 具体细节 怎样 参数被传递给脚本,所以让我们看一下源代码(在编写时是npmv6.14.7)。这个脚本似乎和它的论点连在一起了 here here . 基本上, npm run myscript -- one two three

    sh -c 'if [ "$1" = one ]; then printf %s\\n "$@"; else echo false; fi "one" "two" "three"'
    

    我们的论点 one two three fi . sh 金融机构 只是一个注定的结局 if 不需要争论。

    sh -c 'if [ "$1" = one ]; then printf %s\\n "$@"; else echo false; fi' sh "one" "two" "three"
    

    在这里 one , two three 是sh本身的参数,因此成为参数变量 $1 , $2 $3 在给定的脚本中。npm不允许我们直接这样做,但我们可以通过将脚本包装到shell函数中来完成同样的任务:

    "scripts": {
        "myscript": "f() { if [ \"$1\" = one ]; then printf %s\\\\n \"$@\"; else echo false; fi; }; f"
    }
    

    这里的脚本以对函数的调用结束,因此npm将把参数连接到这个调用,最终调用函数 f "one" "two" "three" :

    sh -c 'f() { if [ "$1" = one ]; then printf %s\\n "$@"; else echo false; fi; }; f "one" "two" "three"'