前言
在实际开发工作中,我们经常使用命令行进行日志分析、程序部署、debug程序等工作。在Linux下,|、grep、find、xagrs、awk等工具是非常强大的,可以很容易的完成各种数据处理。在需求比较简单的情况下,我们会直接命令行;如果再复杂一点,我们会编写简单的Shell脚本;如果业务更加复杂,shell已经不适合进行处理了,我们就会使用我们熟悉的语言进行编码,如果你刚好使用Golang,那么可以使用Golang内置的exec.Command完成命令行操作。
简单使用
1
2
3
4
5
6
7
8
9
10
11
|
func main() { // # grep 321 2022053015.log command := exec.Command( "grep" , "321" , "2022053015.log" ) out := bytes.NewBuffer( nil ) command.Stdout = out command.Stderr = os.Stderr if err := command.Run(); err != nil { log.Fatal(err) } fmt. Println (out. String ()) } |
上面的代码是最简单的一种使用命令行工具的方式,它会直接调用对应工具的程序,然后获取执行结果。然而,如果像下面这样包含通配符,是无法实现我们想要的效果的。因为通配符是Shell程序进行处理的,而我们这里是直接调用grep程序,因此只会去查询是否有精准匹配20220530*.log
名字的文件,不会展开*
。
1
2
3
4
5
6
7
8
9
10
11
|
func main() { // # grep 321 20220530*.log command := exec.Command( "grep" , "321" , "20220530*.log" ) out := bytes.NewBuffer( nil ) command.Stdout = out command.Stderr = os.Stderr if err := command.Run(); err != nil { log.Fatal(err) } fmt. Println (out. String ()) } |
使用Shell执行命令
为了能够使用Shell的能力,我们需要先进入Shell上下文,再输入我们需要的命令。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
func main() { // 进入Shell上下文 command := exec.Command( "sh" ) in := bytes.NewBuffer( nil ) out := bytes.NewBuffer( nil ) command.Stdin = in command.Stdout = out command.Stderr = os.Stderr // 输入命令,记得每个命令最后以换行符结束,这样Shell才会执行这个命令 grepCmd := fmt.Sprintf( "grep %s %s*.log\n" , "321" , "20220530" ) in.WriteString(grepCmd) // 完成之后退出Shell上下文 in.WriteString( "exit\n" ) if err := command.Run(); err != nil { log.Fatal(err) } fmt. Println (out. String ()) } |
简单封装Shell执行命令
上面的代码核心只有grepCmd := fmt.Sprintf("grep %s %s*.log\n", "321", "20220530")
这一行,其他的基本上都是模板代码,因此最好简单封装一下,避免到处拷贝代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 执行shell命令 func Exec(cmd string ) (*bytes.Buffer, error ) { command := exec.Command( "sh" ) in := bytes.NewBuffer( nil ) out := bytes.NewBuffer( nil ) command.Stdin = in command.Stdout = out command.Stderr = os.Stderr in.WriteString(cmd) in.WriteString( "exit\n" ) return out, command.Run() } func main() { grepCmd := fmt.Sprintf( "grep %s %s*.log\n" , "321" , "20220530" ) out, err := Exec(grepCmd) if err != nil { log.Fatal(err) } fmt. Println (out. String ()) } |
到此这篇关于Golang操作命令行的几种方式总结的文章就介绍到这了,更多相关Golang命令行操作内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/7103415182159773727