Programmers want to create command-line programs for the following reasons:
1. Create scripts for that can be run automatically on a regular basis.
2. To create a script that interacts with files in the system.
3. To create scripts that can perform system maintenance tasks.
4. To avoid the unnecessary overhead of designing graphical user interfaces.
On the Mac os terminal, enter the command line:
vim beatles.txt
Open vim and enter the following:
John Paul Ringo George
Save and exit.
Enter the command line as follows:
sort beatles.txt
The operation results are as follows:
George John Paul Ringo
Operation input and output
name | code | describe |
Standard input | 0 | Contains the input provided to the program |
standard output | 1 | Contains the output displayed on the screen |
Standard error | 2 | Contains error messages that are displayed on the screen |
Enter the command line and delete Beatles Txt, as follows:
rm beatles.txt
Enter the command line again as follows:
sort beatles.txt
The operation results are as follows:
sort: No such file or directory
Access the command line parameters, and the program list is as follows:
package main import( "fmt" "os" ) func main(){ for i,arg:=range os.Args{ fmt.Println("argument",i,"is",arg) } }
Enter the command line twice as follows:
go build main.go ./main
The operation results are as follows:
argument 0 is ./main
Enter the command line as follows:
./main for bar baz
The operation results are as follows:
argument 0 is ./main argument 1 is for argument 2 is bar argument 3 is baz
Enter the command line as follows:
go run main.go
The operation results are as follows:
argument 0 is /var/folders/3x/txs8lfzs6s13njkkrvjmnz2c0000gn/T/go-build2259276456/b001/exe/main
Analyze the command line flag, and the program list is as follows:
package main import( "fmt" "flag" ) func main(){ s:=flag.String("s","Hello World","String help text") flag.Parse() fmt.Println("value of s:",*s) }
Enter the command line twice as follows:
go build main.go ./main
The operation results are as follows:
value of s: Hello World
Enter the command line as follows:
./main -s Goodbye
The operation results are as follows:
value of s: Goodbye
Enter the command line as follows: (- h, -- h, - help, -- help)
./main -h
The operation results are as follows:
Usage of ./main: -s string String help text (default "Hello World")
Specifies the type of flag
The flag package analyzes the type of flag according to the declaration, which corresponds to the type system of Go language.
Analyze String, Int and Boolean flags. The program list is as follows:
package main import( "flag" "fmt" ) func main(){ s:=flag.String("s","Hello world","String help text") i:=flag.Int("i",1,"Int help text") b:=flag.Bool("b",false,"Bool help text") flag.Parse() fmt.Println("value of s:",*s) fmt.Println("value of i:",*i) fmt.Println("value of b:",*b) }
Enter the command line twice as follows:
go build main.go ./main
The operation results are as follows:
value of s: Hello world value of i: 1 value of b: false
Enter the command line as follows:
./main -s Goodbye -i 42 -b
The operation results are as follows:
value of s: Goodbye value of i: 42 value of b: true
Enter the command line as follows:
./main -i String
The operation results are as follows:
invalid value "String" for flag -i: parse error Usage of ./main: -b Bool help text -i int Int help text (default 1) -s string String help text (default "Hello world")
If the user executes the command-line program with the wrong class of the value specified for the flag, an error message is displayed. In the above example, set the flag - i to String. Since this flag must be set to an integer value, it will cause an error: the default behavior of the flag package is to print an error message and display help text.
Custom Help text
Create help text for the command line tool. The program list is as follows:
package main import( "flag" "fmt" "os" ) func main(){ flag.Usage=func(){ usageText:=`Usage example [OPTION] An example of customizing usage output -s,--s example string argument, default: String help text -i,--i example integer argument, default: Int help text -b,--b example boolean argument, default: Bool help text` fmt.Fprintf(os.Stderr,"%s\n",usageText) } s:=flag.String("s","Hello world","String help text") i:=flag.Int("i",1,"Int help text") b:=flag.Bool("b",true,"Bool help text") flag.Parse() fmt.Println("value of s:",*s) fmt.Println("value of i:",*i) fmt.Println("value of b:",*b) }
Enter the command line twice as follows: you can also specify the option - h.
go build main.go ./main --help
The operation results are as follows:
Usage example [OPTION] An example of customizing usage output -s,--s example string argument, default: String help text -i,--i example integer argument, default: Int help text -b,--b example boolean argument, default: Bool help text
Enter the command line ". / main" and the running results are as follows:
value of s: Hello world value of i: 1 value of b: true
The flag package will automatically generate help text. The variable Usage is set to a function, so that this function will be called whenever an error occurs in the process of analyzing the flag.
Use the os package in the standard library to print the message to the standard Error, because this message will be displayed when an analysis error is found, but the output is completely customizable.
Create subcommand
Many command-line programs support subcommands.
To create a subcommand and specify a flag:
cloneCmd:=flag.NewFlagSet("clone",flag.ExitOnerror)
The first parameter is the subcommand name, and the second parameter specifies the error handling behavior.
flag.ContinueOnError: if there is no analysis error, continue to execute.
flag.ExitOnError: if there is an analysis error, exit and set the status code to 2.
flag. Panic onerror: if an analysis error occurs, panic is raised.
Use subcommands in the command line program. The program list is as follows:
package main import( "flag" "fmt" "os" "strings" ) func flagUsage(){ usageText:=`example is an example cli tool. Usage: example command [arguments] The commands are: uppercase uppercase a string lowercase lowercase a string Use "example [command] --help" for more information about a command.` fmt.Fprintf(os.Stderr,"%s\n",usageText) } func main(){ flag.Usage=flagUsage uppercaseCmd:=flag.NewFlagSet("uppercase",flag.ExitOnError) lowercaseCmd:=flag.NewFlagSet("lowercase",flag.ExitOnError) if len(os.Args)==1{ flag.Usage() return } switch os.Args[1]{ case "uppercase": s:=uppercaseCmd.String("s","","A string of text to be upercased") uppercaseCmd.Parse(os.Args[2:]) fmt.Println(strings.ToUpper(*s)) case "lowercase": s:=lowercaseCmd.String("s","","A string of text to be lowercased") lowercaseCmd.Parse(os.Args[2:]) fmt.Println(strings.ToLower(*s)) default: flag.Usage() } }
Enter the command line as follows:
./main uppercase -s "i want to grow up"
The operation results are as follows:
I WANT TO GROW UP
Enter the command line as follows:
./main lowercase -s "I DO NOT WANT TO GROW UP"
The operation results are as follows:
i do not want to grow up
POSIX compatibility: omitted.
Install and share command line programs
To make Go tools work, you must follow the Go language conventions. $GOPATH must be set correctly. Use the standard target layout and place the code in a subfolder located in src.
|-bin
|-pkg
|-src
|-github.com
The path of the subfolder is as follows:
$GOPATH/src/github.com/douxiaobo/
The Go project is located in this folder. Create a folder named heloworld in this folder as follows:
// Linux / macOS
$ mkdir -p $GOPATH/src/github.com/[your github username]/helloworld
// Windows
$ mkdir "$GOPATH\src\github.com\[your github username]\helloworld"
Access the command line parameters, and the program list is as follows:
package main import( "fmt" ) func main(){ fmt.Println("Hurray! You are a Gopher!") }
Use the command GO install to install the program. The specified path must be relative to $GOPATH.
The command line is as follows:
go install github.com/[your github usrername]/helloworld
Submit the code to Github so that others can easily install it with the following command line:
go get github.com/[your github usrername]/helloworld