Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I pass a dynamic set of arguments to Go's command exec.Command?

Tags:

command

go

exec

I came across a question on here relating to arguments being passed to Go's exec.Command function, and I was wondering if there was a way do pass these arguments dynamically? Here's some sample code from sed question:

package main

import "os/exec"

func main() {
    app := "echo"
    //app := "buah"

    arg0 := "-e"
    arg1 := "Hello world"
    arg2 := "\n\tfrom"
    arg3 := "golang"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3)
    out, err := cmd.Output()

    if err != nil {
        println(err.Error())
        return
    }

    print(string(out))
}

So as you can see each arg is defined above as arg0, arg1, arg2 and arg3. They are passed into the Command function along with the actual command to run, in this case, the app var.

What if I had an array of arguments that always perhaps had an indeterministic count that I wanted to pass through. Is this possible?

like image 653
Harry Lawrence Avatar asked Apr 01 '14 09:04

Harry Lawrence


People also ask

How do you pass arguments in REXX?

Passing Arguments Using the CALL Instruction or REXX Function Call. When you invoke a REXX exec using either the CALL instruction or a REXX function call, you can pass up to 20 arguments to an exec. Each argument must be separated by a comma.

How do you implement command-line arguments in go?

Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program. In Golang, we have a package called as os package that contains an array called as “Args”.

What is exec in golang?

It is simply a sub-package that allows you to execute external commands using Go.

What is exec command?

The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).


1 Answers

Like this:

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

Have a look at the language and tutorial on golang.org.

like image 68
Volker Avatar answered Oct 25 '22 05:10

Volker