Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a command line argument to a nested script?

NOTE: This is NOT about sending args to the top-level script, but to the script called by that script

In my package.json, when I call a script that takes command line args directly, it works. But when I call a script that calls that other script, it's not passing the command line args to it. How do i pass them?

{
    ...
    "takes-args": "somemodule",
    "calls-takes-args": "npm run takes-args"
}

When i run the below command, the args come through:

npm run takes-args -- -env dev

But when I run it through the other script, it never gets the args. Is there some way to pass them down? Maybe by a variable marker like a dollar sign?

//The top-level script gets the args, BUT takes-args does NOT
npm run calls-takes-args -- -env dev

Is there any way?

like image 521
Don Rhummy Avatar asked Jan 06 '23 02:01

Don Rhummy


1 Answers

Your scripts field should look like this:

{
    ...
    "takes-args": "somemodule",
    "calls-takes-args": "npm run takes-args --"
}

Notice the -- at the end of calls-takes-args.

Anything you pass after the -- is directly appended onto the script you are running. When you run npm run calls-takes-args -- -env dev, that is the equivalent of running npm run takes-args -env dev. Of course, that does not work.

If you add the -- to calls-takes-args, when you run npm run calls-takes-args -- -env dev, npm run runs npm run takes-args -- -env dev. Success!

If you don't pass any args to calls-takes-args, the trailing -- won't hurt.


Edit:

If you can't/don't want to modify your package.json, you can run

npm run calls-takes-args -- -- -env dev

That will run somemodule -env dev.

like image 156
RyanZim Avatar answered Jan 07 '23 14:01

RyanZim