0%

Golang调用shell脚本

前言

今天在用一些工具处理文件的时候,批量手动操作真会累死人,时间成本不划算,想着怎么用脚本做成自动化,思路大概是每个脚本处理不同的功能,也就没必要将所有功能写到一个脚本了,担心万一某个模块出了问题影响整个流程。然后其中一个功能需要调用某个网页的接口处理,想了好久,请教了下一些前辈,给出的建议就是破解接口,这时候我立刻想到了Go…大概分三步:

  • shell调用工具拿到处理好的数据
  • 再由Go实现对接口的数据请求…
  • 请求回来接口之后再交由shell调用工具做最后的处理,从而完成整个模块的工作。

这里记住一点:shell脚本无非就做成参数形式。

API

os/exec包可用于从Go触发任何OS命令。 相同的可用于触发.sh文件。

具体函数接口参考官方文档package exec

上代码

首先,在同一目录中创建一个test.sh文件

1
2
3
4
#!/bin/bash

your_name="start test ..."
echo $your_name

执行chmod +x test.sh,不然会因为没有执行权限报错:

1
Execute Shell:./test.sh failed with error:exit status 126%

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"fmt"
"os/exec"
)

func main() {
fmt.Println("1")

command := `./test.sh .`
cmd := exec.Command("/bin/bash", "-c", command)

output, err := cmd.Output()
if err != nil {
fmt.Printf("Execute Shell:%s failed with error:%s", command, err.Error())
return
}
fmt.Printf("Execute Shell:%s finished with output:\n%s", command, string(output))
}

输出

1
2
3
1
Execute Shell:./test.sh . finished with output:
start test ...

https://golangbyexample.com//