ls 命令
lsls
lslsls -a.
此命令还有很多功能,这一节的重点是命令行程度的编写,就实现上面四个。
os.Args 读取参数
定义如下,一个数组。该数组长度由参数个数决定,第一个参数为程序本身,后面为参数列表。
var Args []string
ls -lArgs=["ls","-l"]ls
func main() {
targetDirPath := "./"
if len(os.Args) > 1 {
targetDirPath = os.Args[1]
}
if dirList, err := ioutil.ReadDir(targetDirPath); err == nil {
for _, dirInfo := range dirList {
fmt.Print(dirInfo.Name() + " ")
}
} else {
fmt.Println(err.Error())
}
}
os.Agrsioutil.ReadDir[] FileInfoerror
输出
$ go build -o ls main.go
$ ./ls
main.go folder ls
$ ./ls folder
file1 file2
-os.Args
pflag
Goflagpflagflagpflagflag
flaguintuint64pflaguint8uint16int32ipip maskip netcountsliceflagFlagFlagSetpflagflagshorthanddeprecatedhidden
var a = pflag.BoolP("all", "a", false, "Include directory entries whose names begin with a dot (.).")
var help = pflag.BoolP("help", "h", false, "Show this help message.")
pflag.Parse()
if *help {
pflag.Usage()
return
}
args := pflag.Args()
if len(args) == 0 {
args = append(args, "./")
}
if len(args) == 1 {
ShowPath(args[0], *a)
} else {
for _, v := range args {
fmt.Println(v + ":")
ShowPath(v, *a)
}
}
ShowPathboolpflag.BoolPbool--all-apflag.Parse()pflag.Usage()
ls
$ go build -o ls main.go $ ./ls folder go.mod go.sum main.go $ ./ls -a . .. .git folder go.mod go.sum main.go $ ./ls ./ folder ./: folder go.mod go.sum main.go folder: file1 file2 $ ./ls -h Usage of ./ls: -a, --all Include directory entries whose names begin with a dot (.). -h, --help Show this help message.
是不是相当给力啦!
小结
命令行读取一共有五个常用的包
os.ArgsflagGopflagcobraviper
bin