Exec command with variable

Hey i have a variable command with somethings like “mkdir /root/test”
and i want to execute this with a exec command.

But i can t use my variable i don t understand why.

(I try to do that)

	cmd := exec.Command(data.Command)
        err := cmd.Run()
	if err != nil {
		return
	}

Hi @Bagou450,

What does data.Command contain at the moment you create cmd from it?
What does err contain?

Tip: add fmt.Println() to print out these values, this will help better understanding why the code fails.

2 Likes

fork/exec mkdir /root/camarche: no such file or directory the error

i need to use dynamic args i see that on google

args := []string{"what", "ever", "you", "like"}
cmd := exec.Command(app, args...)

but i have a json how i can convert it to []string??

Looks like the path /root/camarche does not exist. Remember that mkdir only creates the last element of the given path. Use mkdir -d to create all missing parent/grand parent/etc directories.

This depends on the structure of your JSON data. Usually, the encoding/json package should have all you need. If your JSON data is a string array, json.Unmarshal should be able to read this data straight away into a slice of strings.

My understanding is you have some structure like this:

type myData struct {
    // ...
    Command string
    // ...
}

var data = myData{
    // ...
    Command: "fork/exec mkdir /root/camarche"
    // ...
}

And you want to run that command with exec.Command. Is that right? If so, will any of the arguments to your commands have spaces? If not, you should be able to use string.Fields:

fields := strings.Fields(data.Command)
cmd := exec.Command(fields[0], fields[1:]...)

If they might have spaces and will be quoted, you will need to parse the arguments. After Googling, it looks like there are packages that can do this for you such as github.com/kballard/go-shellquote which can split your single string into all of the fields.