How to call a shell script in Golang?
In Golang, you can use the os/exec package to execute shell scripts.
Here is a simple example:
package main
import (
"log"
"os/exec"
)
func main() {
// 创建一个cmd命令
cmd := exec.Command("/bin/sh", "-c", "your_shell_script.sh")
// 执行命令并等待执行完成
err := cmd.Run()
if err != nil {
log.Fatalf("执行命令时发生错误:%v", err)
}
}
In the example above, we used the exec.Command function to create a cmd command with the argument /bin/sh -c your_shell_script.sh, indicating that we want to run a shell script. Then, we called the cmd.Run() method to execute the command and waited for it to finish. If an error occurred during execution, we used log.Fatalf to print the error message and exit the program.
It is important to note that when calling a shell script, if the script file is not in the current working directory, you need to specify the absolute or relative path of the script file.
Alternatively, if you need to access the output of a shell script, you can use the cmd.Output() method to retrieve the output as a byte slice. For example:
package main
import (
"log"
"os/exec"
)
func main() {
cmd := exec.Command("/bin/sh", "-c", "your_shell_script.sh")
// 获取输出结果
output, err := cmd.Output()
if err != nil {
log.Fatalf("执行命令时发生错误:%v", err)
}
// 将输出结果转换为字符串并打印
log.Println(string(output))
}
The example above will transform the output results into a string and print them using log.Println.
I hope this helps you!