14

I am using Go 1.10.2 on Mac (darwin/amd64) and facing this error. It's saying no such file or directory.

Here's my code,

func loop1(gor_name string, ras_ip string) {
    var a string
    var c string
    a = search_path()
    fmt.Printf("当前路径为", a)
    fmt.Println(os.Chdir(a))

    c = fmt.Sprintf("%s %s %s %s", "./goreplay  --input-file ", gor_name, " --input-file-loop --output-http ", ras_ip)
    fmt.Printf("c:  ", c)
    cmd := exec.Command(c)
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
    channel <- 1

}

Thanks a lot for any suggestions.

3 Answers 3

27

The function signature for exec.Command is:

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

where name is the name of the program and args are the arguments. Try this:

cmd := exec.Command("./goreplay", "--input-file", gor_name, "--input-file-loop", "--output-http", ras_ip)
Sign up to request clarification or add additional context in comments.

1 Comment

as is shown no spaces are allowed in front or behind parms
0

This answer is just an information on @cerise-limon answer.

The exec command requires command and then the arguments.
The string of command and args will throw the same error.

Pass the command to exec following with the comma separated args.

Comments

-1

The other way to do is:

type Client struct {
    logger *logrus.Entry
}

const shell = "/bin/bash"

// Execute executes the provided command
func (c *Client) Execute(command []string) (bool, error) {

    c.logger.Info("Executing command ", shell, " -c ", strings.Join(command, " "))

    output, err := exec.Command(shell, "-c", strings.Join(command, " ")).Output()

    if err != nil {
        return false, err
    }

    c.logger.Info(string(output))

    return true, nil
}

func GetBashClient() *Client {
    logger := logrus.NewEntry(logrus.StandardLogger())
    return &Client{logger: logger}
}

Now you can call

command := []string{
    "/usr/bin/<your script>.sh",
    args1,
    args2
}

GetBashClient().Execute(command)

3 Comments

@CeriseLimón that is not correct, if you check the code, the arguments is passed as parameters to "<your script.sh>" which is executed in /bin/bash shell, and your script is responsible for handling what you want to do with the arguments.
I see what you are saying, but that's the contract between your_script.sh and go code, you can decide to pass named parameters.
Like I said you could use named parameter, you can establish the contract between yourscript.sh and the actual parameters being passed, ./yourscript.sh, --named_param1=a b, --named_param2=c, like explained above, it depends on your requirements and how you write arg parser in yourscript.sh. Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.