【问题标题】:pass parameters to bash script through npm run通过 npm run 将参数传递给 bash 脚本
【发布时间】:2019-02-08 03:31:16
【问题描述】:

我是编写 bash 脚本的新手,我创建了一个 npm 包 https://www.npmjs.com/package/comgen

重击

days=3
hours=24
minutes=60
totalNumberOfCommits=3
lenghtOfTime=$((days*hours*minutes))
arrayOfCommits=$(shuf -i 1-$lenghtOfTime -n $totalNumberOfCommits | sort -r -n)

for index in $arrayOfCommits
  do
    randomMessage=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)  
    git commit --allow-empty --date "$(date -d "-$index minutes")" -m "$randomMessage"
  done 
git push origin master

你像这样运行它npm run comgen我希望它像这样运行:

npm run comgen -days "x number of days" -totalNumberOfCommits "x number of commits"

包.json

"scripts": {
    "comgen": "commit-generator.sh"
 },

通过的天数和提交总数将替换我在 bash 脚本中拥有的变量中的数字。

我在发布自己的帖子之前阅读了这个 SO 问题:https://unix.stackexchange.com/questions/32290/pass-command-line-arguments-to-bash-script

【问题讨论】:

    标签: bash shell npm npm-scripts


    【解决方案1】:

    试试这个

    package.json

    "scripts": {
        "comgen": "commit-generator.sh"
     },
    

    提交生成器.sh

     #!/bin/bash 
    echo $npm_config_days
    echo $npm_config_hours
    

    终于到了终端

    npm run comgen --days=foo --hours=bar
    

    输出:

    > commit-generator.sh
    
    foo
    bar
    

    【讨论】:

      【解决方案2】:

      我不确定npm 究竟是如何工作的,但根据我的经验,我猜想命令行参数会直接传递给被调用的可执行文件(二进制文件或脚本)。这意味着您的脚本实际上被称为

      /path/to/comgen -days "x number of days" -totalNumberOfCommits "x number of commits"
      

      现在解析 cmdline 参数是纯 Bash 的东西。您评估一个选项并决定下一个值是什么:

      days=3
      hours=24
      minutes=60
      totalNumberOfCommits=3
      
      while [ $# -ne 0 ]; do
        case "$1" in
          "-d"|"-days") days=$2; shift 2;;
          "-tc"|"-totalNumberOfCommits") totalNumberOfCommits=$2; shift 2;;
        # "-x"|"-xx"|"-xxx") : Process another option; shift 2;;
          *) break;;
        esac
      done
      
      lenghtOfTime=$((days*hours*minutes))
      
      ... rest of the code
      

      【讨论】:

      • 我现在要做的就是将变量传递给 npm run comgen -d 5 -tc 10
      • 我已经到了可以在终端中运行这个commit-generator.sh -d 4 -tc 10 的地步。现在,当我想做 npm run comgen -d 5 -tc 10 我在我的 package.json 中得到 commit-generator.sh -d $1 -tc $2 "1" "10" 我有 "scripts": { "comgen": "commit-generator.sh -d $1 -tc $2 " }
      • 我想通了。我的问题是我需要传递不带“-”的参数并将 bash 脚本中的名称更改为 d、tc 等
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 2014-10-04
      • 2023-03-05
      • 2022-01-27
      • 2015-07-12
      • 2016-05-27
      • 2021-11-18
      相关资源
      最近更新 更多