Pass negative number as command line argument

Is there a way to pass a negative number as an option or command line argument to ArgumentParser?

For example, the code below generates an error when I try to pass a -5 as the optional value.

% ./parsetest2        
num = 3

% ./parsetest2 --num 5
num = 5

%./parsetest2 --num -5
Error: Missing value for '--num <num>'
Help:  --num <num>  Specify a number as an option
Usage: print-number [--num <num>]
  See 'print-number --help' for more information.

The code:

import Foundation
import ArgumentParser

struct PrintNumber: ParsableCommand {
    @Option(help: "Specify a number as an option")
    var num: Int = 3
    
    func run() {
        print("num = \(num)")
    }
}

PrintNumber.main()

I have resolved it: Use the "=" sign

% ./parsetest2 --num=-5
num = -5

1 Like

Small observation along the same line as a negative number for an option: in the Math example code, the sequence of numbers for the argument must all be positive integers.

% ./parsetest3 add 4 3 5
12

% ./parsetest3 add 4 3 -5
Error: Unknown option '-5'
Usage: math add [--hex-output] [<values> ...]
  See 'math add --help' for more information.

Does this work?

./parsetest3 add -- 4 3 -5
1 Like

To the best of my knowledge, in order to have negative numbers parsed in an array, you'll have to set the parsing strategy to .unconditionalRemaining:

...
@Argument(parsing: .unconditionalRemaining, ...)
var numbers: [Int]
...
1 Like

Does quoting help?

./parsetest2 --num "-5"

Yes! Adding this to my notes

% ./parsetest3 add -- 4 3 -5
2

No. neither single nor double quotes work. The equal and the negative number (without spaces) works.

% ./parsetest2 --num "-5"
Error: Missing value for '--num <num>'
Help:  --num <num>  Specify a number as an option
Usage: print-number [--num <num>]

./parsetest2 --num=-5  
num = -5

This works too. Thanks!

@Argument(
        parsing: .unconditionalRemaining,
        help: "A group of integers to operate on.")
    var values: [Int] = []

and then executing the code

% ./parsetest3 add 3 4 -5
2

% ./parsetest3 add -5 -4 -3
-12
1 Like

Unfortunately, quotes are processed at the shell level, so no program ever even sees the quotes you write and an Argument Parser executable can't make any parsing decisions based on that.

2 Likes