SoFunction
Updated on 2025-03-05

Implementing the linux command ls command through Golang (command line tool building)

ls command

To achievels, let's review firstlsOrder.

  • lsNo parameters are added to indicate querying files/folders in the current directory
  • lsAdd a path after it, list all, and do not include hidden files/folders
  • ls -aList all, including.Hidden files at the beginning

This command has many functions. The focus of this section is on writing command line level, so it implements the above four.

Read parameters

Defined as follows, an array. The length of the array is determined by the number of parameters. The first parameter is the program itself and the parameter list is followed.

var Args []string

for examplels -lArgs=["ls","-l"], we now implement itls+ Directory, or default directory, the default current directory code is as follows.

func main() {
	targetDirPath := "./"
	if len() > 1 {
		targetDirPath = [1]
	}

	if dirList, err := (targetDirPath); err == nil {
		for _, dirInfo := range dirList {
			(() + " ")
		}
	} else {
		(())
	}
}
  • useTo get the parameters of the incoming program
  • useRead the directory and return the value[] FileInfoTraversal, output directory/file information
  • Will encountererrorOutput to terminal

Output

$ go build -o ls
$ ./ls 
folder ls
$ ./ls folder
file1 file2

Look, we have implemented it simply. But we will find that to use-When starting parameters, useThis also requires more complicated logic to hand-written to determine whether the input is a path or other parameters, so the next package is on the scene.

pflag

Yesterday's DailyGoAlready saidflagBag,pflagPackage andflagThe working principle of the package and even the code implementation are similar. The following ispflagrelativelyflagSome advantages:

  • Supports more granular parameter types: for example,flagOnly supporteduintanduint64,andpflagAdditional supportuint8uint16int32etc.
  • Supports more parameter types:ipip maskip netcount, and all types ofslicetype.
  • Compatibility standardsflagLibraryFlagandFlagSetpflagMore like rightflagextension.
  • Native support richer features: supportshorthanddeprecatedhiddenAdvanced features such as
var a = ("all", "a", false, "Include directory entries whose names begin with a dot (.).")
	var help = ("help", "h", false, "Show this help message.")
	()
	if *help {
		()
		return
	}
	args := ()
	if len(args) == 0 {
		args = append(args, "./")
	}
	if len(args) == 1 {
		ShowPath(args[0], *a)
	} else {
		for _, v := range args {
			(v + ":")
			ShowPath(v, *a)
		}
	}
  • The way to list the folders is writtenShowPathIn the function, the second parameter isboolIf you are interested in determining whether to list all files (including hidden files) you are interested in looking at my source code. This is not the point.
  • Define aboolType parameters, support long and short parameters--all,-a, the return value is a pointer.
  • ()Call this function and set the parameter value to the pointer of the corresponding pointer.
  • ()Usage Print.

This way we'll achieve itlsbasic functions. Test it.

$ go build -o ls 
$ ./ls
folder    
$ ./ls -a
. .. .git folder    
$ ./ls ./ folder 
./:
folder    
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.

Isn't it quite powerful?

summary

There are five commonly used packages for reading command line

  • Parameter analysis provided by the system package.
  • flag: Simple parameter analysis, yesterday's daily oneGoShared.
  • pflag: Command line parameter analysis.
  • cobra: Apply the command line framework and share it another day.
  • viper: Configuration file, environment variable, command line, buffer. Today, I have shared the daily Go in the group, so I won’t say much.

Command line tools, you just need to give executable permissions and then put them inbinIn it, it will become a system command to facilitate you to do more things, such as backup databases and other actions, and improve your operation and maintenance efficiency. Oh, right, the source code is here:/golang-minibear2333/cmd_utils

The above is the detailed content of implementing the linux command ls command (command line tool building) through Golang. For more information about Golang command line tools, please pay attention to my other related articles!