通过npm run将参数传递给bash脚本

时间:2018-09-03 05:27:27

标签: bash shell npm npm-scripts

我是写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"

Package.json

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

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

我在张贴自己的https://unix.stackexchange.com/questions/32290/pass-command-line-arguments-to-bash-script

之前先阅读了此类问题

2 个答案:

答案 0 :(得分:1)

我不确定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

答案 1 :(得分:0)

试试这个

package.json

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

commit-generator.sh

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

最后在终端

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

输出:

> commit-generator.sh

foo
bar
相关问题