在用exec.Comand()的时候出现cat /etc/hosts都报错,显示没有这个文件或目录(no such file…),试了试其他命令也大多是过不了的。
问了同事说如果环境变量没问题或者hosts没配错就是shell封装
原:
command := exec.Command(cmd, parameter)
更改为:
command := exec.Command("bash", "-c", c)
调用的函数完整代码如下:(注释掉了原来的代码)

func RunCommand(c string) ([]byte, error) {
	// cmd := exec.Command(c)
	// return cmd.CombinedOutput()
	// c = strings.Trim(c, " ")
	// index := strings.Index(c, " ")
	// if index < 0 {
	//  	return nil, errors.New("invalid command")
	//}

	// cmd := c[0:index]
	// parameter := c[index:]
	// logs.Debug("Running command: %s", c)
	// command := exec.Command(cmd, parameter)
	command := exec.Command("bash", "-c", c)
	return command.CombinedOutput()
}

就是加个bash -c
具体原理,刚学golang,还没搞懂。留一个坑

更多推荐