Go Command Line Parsing: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
(5 intermediate revisions by the same user not shown)
Line 4: Line 4:


=Overview=
=Overview=
Simple access to command line argument is provided by <tt>[[Go_Package_os#os.Args|os.Args]]</tt>. <tt>os.Args</tt> is a string slice that holds the command-line arguments, starting with the program name, which is present on position 0
<pre>
for i, arg := range os.Args {
    fmt.Printf("argument %d: %s\n", i, arg)
}
</pre>


Go provides support for command line "flag" parsing in the [[Go Package flag|flag package]].
Go provides support for command line "flag" parsing in the [[Go Package flag|flag package]].
Line 10: Line 18:


<pre>
<pre>
sPtr := flag.Int("s", ".", "the path vale")
sPtr := flag.String("s", ".", "the path vale")
iPtr := flag.Int("i", 1, "the i value")
iPtr := flag.Int("i", 1, "the i value")
</pre>
</pre>
Line 23: Line 31:


<pre>
<pre>
    fmt.Println("flag s value: ", *sPtr)
fmt.Println("flag s value: ", *sPtr)
    fmt.Println("flag i value: ", *iPtr)
fmt.Println("flag i value: ", *iPtr)
</pre>
 
The rest of the command line arguments can be retrieved with <tt>flag.Args()</tt> that returns a <tt>string</tt> slice.
 
=In-Line Documentation=
 
If a flag the program does not know about is specified, it produces an output like this:
 
<pre>
NOMBP2:bakm ovidiu$ ./output/bakm -version
flag provided but not defined: -version
Usage of ./output/bakm:
  -keep int
    the number of files to keep in the directory (default 10)
</pre>
</pre>



Latest revision as of 04:48, 5 April 2016

Internal

Overview

Simple access to command line argument is provided by os.Args. os.Args is a string slice that holds the command-line arguments, starting with the program name, which is present on position 0

for i, arg := range os.Args {
    fmt.Printf("argument %d: %s\n", i, arg)
}

Go provides support for command line "flag" parsing in the flag package.

Flags (example: "-path=/something" or "-max=100") are declared with:

sPtr := flag.String("s", ".", "the path vale")
iPtr := flag.Int("i", 1, "the i value")

Note that the flag declaration methods return pointers that can be used to read the value of the flags after parsing:

flag.Parse()

Then their value is read from the previously obtained pointers:

fmt.Println("flag s value: ", *sPtr)
fmt.Println("flag i value: ", *iPtr)

The rest of the command line arguments can be retrieved with flag.Args() that returns a string slice.

In-Line Documentation

If a flag the program does not know about is specified, it produces an output like this:

NOMBP2:bakm ovidiu$ ./output/bakm -version
flag provided but not defined: -version
Usage of ./output/bakm:
  -keep int
    	the number of files to keep in the directory (default 10)

Example

playground/go/command-line-args/command-line-arg-parser.go