4

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Strange. What OS/bash versions do you use? And can you paste the exact command you are trying to call? You could also try: FLAGS="path/to/file/2"; npm run scriptcommand (with ';') Note that this however will leave the variable set for subsequent commands, unless you unset/change its value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.