1

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()?

TieDad
  • 9,143
  • 5
  • 32
  • 58
  • 3
    You can pass the commands to a shell application, e.g. `bash`. So try to run `exec.Command()` with `bash -c 'cmd1 && cmd2'` – icza Nov 14 '22 at 10:33
  • 3
    What @icza said: `os.system` takes a string and passes it to a shell, which it executes. Go has no direct support for this, but you can use `os.Getenv` to fetch the value of the `SHELL` environment variable, fall back to `/bin/sh` if it's missing/empty, and execute it passing it the source string as the argument to the `-c` shell's parameter. – kostix Nov 14 '22 at 11:01

1 Answers1

3

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

package main

import (
    "fmt"
    "os"
    "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
Dr Claw
  • 636
  • 4
  • 15