dcas
dcas

Reputation: 451

Run script with variables from package.json?

I work on a Node.js project and often run a command in bash which looks like this:

path/to/file/1 --flags path/to/file/2 --flags somecommand

The command is mostly the same, I only change path/to/file/2 all the time. Now I would like to implement a script into my package.json file so I can run something like this:

npm run scriptcommand path/to/file/2

I don't know much about bash but I feel like I would need something like this in my package.json file:

{
  "scripts": {
    "scriptcommand": "path/to/file/1 --flags $1 --flags somecommand"
  }
}

Is there any posibility to substitute path/to/file/2 with a variable like in the above example so I can set a different path on every run?

Upvotes: 4

Views: 4559

Answers (2)

FoundNil
FoundNil

Reputation: 401

Make a new file to hold your script

scriptcommand.sh

#!/usr/bin/env bash
path/to/file/1 --flags $1 --flags somecommand

probably need to chmod it

sudo chmod +x scriptcommand.sh

package.json

{
  "scripts": {
    "scriptcommand": "scriptcommand.sh"
  }
}

And then to run it use

npm run scriptcommand -- "path/to/file/2"

Notice the -- this tells npm to pass along any remaining arguments to your script.

Upvotes: 1

dgeorgiev
dgeorgiev

Reputation: 941

You can try the following:

"scripts": {
    "scriptcommand": "/bin/echo --flags $FLAGS --flags somecommand"},

FLAGS="path/to/file/2" npm run scriptcommand

Essentially, you set an environment variable, which you use in your scripts command.

Upvotes: 1

Related Questions