How to Run the Shell in the Go Language

Asked 2 years ago, Updated 2 years ago, 65 views

What should I do if I want to type a command from the Go language?

Ruby does it just by enclosing it in the back quarter.

go

2022-09-30 20:22

2 Answers

http://golang.org/pkg/os/exec/ #example_Cmd_Output

package main

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

funcmain(){
    out,err: = exec.Command("date").Output()
    if err!=nil{
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}

http://golang.org/pkg/os/exec/
Depending on the purpose, there are several methods.


2022-09-30 20:22

Ruby backquotes are performed through the shell.Therefore,

`foo-flag`

is actually

$SHELL-c'foo-flag'

Runs as .That is, $SHELL parses the argument and divides it into foo and -flag.
Golang does not have instructions to execute commands through the shell, such as system(3).As erukiti wrote,

exec.Command("foo", "-flag")

Create a Cmd object in the form to get standard output from Output, or

just like ruby's backquote.
exec.Command(os.Getenv("SHELL"), "-c", "foo-flag")

By doing so, I think you will get the expected action.
If you want to split the string into an array that passes to exec.Command, you can use go-shellwords.


2022-09-30 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.