0

I have below scripts in package.json file:

"scripts": {
    "deploy": "deploy.sh service1 && deploy.sh service2 && deploy.sh service3"
}

The deploy.sh script accepts two parameters and the script only specifies one parameter. I'd like to set second parameter via command line, like:

yarn run deploy myName

I'd like to see the script will be translated into deploy.sh service1 myName && deploy.sh service2 myName&& deploy.sh service3 myName

is it possible to do in package.json script? Or I have to write a script file to do that?

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • Does this answer your question? [Pass command line args to npm scripts in package.json](https://stackoverflow.com/questions/51388921/pass-command-line-args-to-npm-scripts-in-package-json) – RobC Jul 31 '20 at 12:26
  • For example: **1)** Change your npm script to: `"deploy": "func() { deploy.sh service1 \"$1\" && deploy.sh service2 \"$1\" && deploy.sh service3 \"$1\"; }; func"` - it utilizes a shell function and in it's body references the first positional parameter, i.e. `$1` references the `myName` argument passed via the command line. **2)** Then run: `npm run deploy -- myName`. _Note: For a cross-platform solution, (which I assume isn't a requirement as you're already using shell scripts), you'd have to shell out via a node.js helper script - similar to "Solution 2" at the linked possible duplicate_. – RobC Jul 31 '20 at 13:35
  • In your option2, if I run `npm run deploy -- myName`, does `myName` attach to every command in the `scripts`? – Joey Yi Zhao Aug 01 '20 at 05:30
  • 1
    To clarify for the option 2 method in your scenario: **1)** Define npm script in _package.json_ as `"deploy": "node ./script.js"` **2)** Either define _script.js_ as; **a)** Using synchronous [`execSync()`](https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options) as per this [script.js](https://paste.ee/p/TnRFP). Or **b)** Using asynchronous [`exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) as per this [script.js](https://paste.ee/p/eBxog) **3)** Run `npm run deploy -- myName`. – RobC Aug 01 '20 at 09:20
  • For option 2 if you wanted to avoid the separate `script.js` file you can inline the code in your npm script using the node.js [`-e`](https://nodejs.org/api/cli.html#cli_e_eval_script) option to evaluate the JS. For instance the following npm script is the same as the previous example _script.js_ that utilizes `execSync()` - albeit slightly refactored: `"deploy": "node -e \"const arg = process.argv[2] || 'quux'; const cmd = ['./deploy.sh service1 ' + arg, './deploy.sh service2 ' + arg, './deploy.sh service3 ' + arg].join(' && '); require('child_process').execSync(cmd, { stdio:[0, 1, 2] });\""` – RobC Aug 01 '20 at 09:35

0 Answers0