Can we convert a line into slices of words?

Hello, as we know golang doesn’t support long Linux commands like service httpd restart
we have to run it via exec.Command(“service”,“https”,“restart”).Output()

What am thinking is to create an function called shell_exec() which takes an string argument and convert it to slices by space and we can run the command via exec.Command
Like shell_exec("service httpd restart")
then shell_exec function will convert sercice httpd restart to three different words service httpd restart
and then we can able to send these words to exec.Command().Output()

Anyone have any idea ?

Hi there,
you can use strings.Split function https://golang.org/pkg/strings/#Split
e.g.:

// command - a parameter of shell_exec
args := strings.Split(command, " ")
exec.Command(args...).Output()

In VS Code , at ... i’m getting this error - can only use ... with matching parameter compiler
and when using go build , i’m getting this error :

# command-line-arguments
./gocmd.go:14:27: not enough arguments in call to exec.Command
        have ([]string...)
        want (string, ...string)

To match the function signature, it needs to be written as

exec.Command(args[0], args[1:]...)
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.