Is there a equvilant of Python's `os.system()` in Golang?

Issue

I want to create a wrapper program that can wrapper whatever shell commands user provides, like:

./wrapper "cmd1 && cmd2"

In Python, I can call os.system("cmd1 && cmd2"). But Golang’s exec.Command needs a list for command and args. Is there way in Golang to archive the same as Python’s os.system()?

Solution

os/exec https://pkg.go.dev/os/exec

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("/usr/bin/bash", "-c", os.Args[1])
    output, err := cmd.CombinedOutput()
    if err != nil {
        panic(err)
    }
    fmt.Println(string(output))
}
$ go run main.go "ls -alh && pwd"
total 4.0K
drwxr-xr-x  2 xxxx xxxx 120 Nov 14 11:12 .
drwxrwxrwt 17 root root 420 Nov 14 11:42 ..
-rw-r--r--  1 xxxx xxxx 217 Nov 14 11:42 main.go
/tmp/stk

Answered By – Dr Claw

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.