PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

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

 July 22, 2022     command, exec, go     No comments   

Issue

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?


Solution

Like this:

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

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



Answered By - Volker
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing