minimistjs / minimist

parse argument options
MIT License
515 stars 30 forks source link

Negative numbers are parsed as new arguments #50

Closed dkurth closed 9 months ago

dkurth commented 9 months ago

I tried using minimist to write a command line tool that accepts a latitude and longitude, but I ran into a problem when one of the values is negative. You can see the issue by simply dumping the parsed arguments, like this:

// dump.js
var argv = require("minimist")(process.argv.slice(2));
console.log(JSON.stringify(argv, null, 2));

Try running this: node dump.js --lat 34.0168729 --long -118.3459323

Since the longitude is negative, it starts with a "-", so apparently it is being interpreted as a new argument. The output looks like this:

{
  "1": true,
  "8": 0.3459323,
  "_": [],
  "lat": 34.0168729,
  "long": true
}

I expected that to be:

{
  "_": [],
  "lat": 34.0168729,
  "long": -118.3459323
}

I tried quoting the negative value, but this did not help.

ljharb commented 9 months ago

Double-dashed arguments usually should use =, ie, --long=-118.3459323. Does that work?

shadowspawn commented 9 months ago

Arguments which start with a dash are assumed to be options and not used as option-values.

The work-around is to be explicit and embed the option value in the argument with an = like:

node dump.js --lat=34.0168729 --long=-118.3459323

I tried quoting the negative value, but this did not help.

As a side-note on why this did not work, quotes around an argument are usually removed by the shell before they reach node and minimist. Quotes can help with special shell characters like $ in arguments, and with spaces within an argument, but don't help with how - is processed.

dkurth commented 9 months ago

Thank you @ljharb and @shadowspawn -- you are right, adding an "=" resolves this. I should have thought to try that!