publish command-line-arguments and command-line-flags
This commit is contained in:
@@ -1,23 +1,26 @@
|
||||
// Use `os.Args` to access command-line arguments and
|
||||
// the name of the program.
|
||||
// [_Command-line arguments_](http://en.wikipedia.org/wiki/Command-line_interface#Arguments)
|
||||
// are a common way to parameterize execution of programs.
|
||||
// For example, `go run hello.go` uses `run` and
|
||||
// `hello.go` arguments to the `go` program.
|
||||
|
||||
package main
|
||||
|
||||
import "os"
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
// `os.Args` includes the program name as the first
|
||||
// value.
|
||||
|
||||
// `os.Args` provides access to raw command-line
|
||||
// arguments. Note that the first value in this slice
|
||||
// is the path to the program, and `os.Args[1:]`
|
||||
// holds the arguments to the program.
|
||||
argsWithProg := os.Args
|
||||
argsWithoutProg := os.Args[1:]
|
||||
|
||||
// `Args` are a slice, you can get individual args
|
||||
// with normal indexing.
|
||||
// You can get individual args with normal indexing.
|
||||
arg := os.Args[3]
|
||||
|
||||
fmt.Println(argsWithProg)
|
||||
fmt.Println(argsWithoutProg)
|
||||
fmt.Println(arg)
|
||||
}
|
||||
|
||||
// todo: discuss building before here
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# Build a `command-line-args` binary so that we have
|
||||
# the expected program name.
|
||||
$ go build command-line-arguments
|
||||
|
||||
|
||||
# To experiment with command-line arguments it's best to
|
||||
# build a binary with `go build` first.
|
||||
$ go build command-line-arguments.go
|
||||
$ ./command-line-arguments a b c d
|
||||
[command-line-arguments a b c d]
|
||||
[./command-line-arguments a b c d]
|
||||
[a b c d]
|
||||
c
|
||||
|
||||
# Next we'll look at more advanced command-line processing
|
||||
# with flags.
|
||||
|
||||
Reference in New Issue
Block a user