自作のLinuxコマンドでオプションを追加しよう2までで作成しましたsayコマンドのヘルプの内容を充実させます。
/home/pi/say.go
package main
import (
"flag"
"fmt"
)
func main() {
flag.CommandLine.Usage = func() {
o := flag.CommandLine.Output()
fmt.Fprintf(o, "Usage: say\n")
fmt.Fprintf(o, "Description: Command description etc.\nOptions:\n")
flag.PrintDefaults()
fmt.Fprintf(o, "Copyright 2024 saitodev.co.\n")
}
var msg string
var isAdd = flag.Bool("a", false, "Add exclamation mark(!)")
var repeat = flag.Int("r", 0, "Set the number of repetitions of the output string.")
flag.Parse()
args := flag.Args()
if len(args) == 1 {
msg = args[0]
}
if *repeat > 0 {
var tmp string
for i := 0; i < *repeat; i++ {
tmp += msg
}
msg = tmp
}
if *isAdd {
msg += "!"
}
fmt.Println(msg)
}
前に作成したコードに
flag.CommandLine.Usage = func() { }
を加えることで説明文を充実させることができます。
flag.PrintDefaults()
が
Options:
-a Add exclamation mark(!)
-r int
Set the number of repetitions of the output string.
の出力になりまして、この上下に
fmt.Fprintf(o, "文字列")
で内容を追加します。
$ go build say.go $ sudo mv say /usr/local/bin/ $ say --help
で内容を確認してみましょう。
Usage: say
Description: Command description etc.
Options:
-a Add exclamation mark(!)
-r int
Set the number of repetitions of the output string.
Copyright 2024 saitodev.co.
になりました。