golang exec.Command错误no such file or directory

问题

执行

out, err := exec.Command("grep 172.0.0.1 ~/.ssh/known_hosts | wc -l").Output()

返回RT错误

原因

exec包

func Command(name string, arg ...string) *Cmd

name参数一定要注意

If name contains no path separators, Command uses LookPath to resolve name to a complete path if possible. Otherwise it uses name directly as Path.

name不要写整条命令!!!
name不要写整条命令!!!
name不要写整条命令!!!

重要的事情说三遍

解决办法

第一个name参数是命令的名字或路径,参数一定要挨个传入

out, err := exec.Command("grep", "172.0.0.1",  "~/.ssh/known_hosts").Output()
out, err = exec.Command("wc", "-l",  "~/.ssh/known_hosts").Output()

如果是多命令,写成脚本 grep.sh

out, err := exec.Command("sh", "grep.sh").Output()

golang官宣

Command returns the Cmd struct to execute the named program with the given arguments.

It sets only the Path and Args in the returned structure.

If name contains no path separators, Command uses LookPath to resolve name to a complete path if possible. Otherwise it uses name directly as Path.

The returned Cmd’s Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, Command(“echo”, “hello”). Args[0] is always name, not the possibly resolved Path.

On Windows, processes receive the whole command line as a single string and do their own parsing. Command combines and quotes Args into a command line string with an algorithm compatible with applications using CommandLineToArgvW (which is the most common way). Notable exceptions are msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm. In these or other similar cases, you can do the quoting yourself and provide the full command line in SysProcAttr.CmdLine, leaving Args empty.

package main

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"strings"
)

func main() {
	cmd := exec.Command("tr", "a-z", "A-Z")
	cmd.Stdin = strings.NewReader("some input")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("in all caps: %q\n", out.String())
}
package main

import (
	"log"
	"os"
	"os/exec"
)

func main() {
	cmd := exec.Command("prog")
	cmd.Env = append(os.Environ(),
		"FOO=duplicate_value", // ignored
		"FOO=actual_value",    // this value is used
	)
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

参考
https://golang.org/pkg/os/exec/#Command

猜你喜欢

转载自blog.csdn.net/my_live_123/article/details/88895795