2

Following answer, below is the code to run external command:

package main

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

func main() {
    path, err := exec.LookPath("ls")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("pwd can be found at path: %s \n", path)

    cmd := exec.Command(path, " -l .")
    var out bytes.Buffer
    cmd.Stdout = &out

    err = cmd.Run()
    if err != nil {
        log.Println("after running external command: ", err)
    }

    log.Println("buffer output:", out.String())
}

Below is the output:

2023/10/22 10:45:03 ls can be found at path: /usr/bin/ls 
2023/10/22 10:45:03 after running external command:  exit status 2
2023/10/22 10:45:03 buffer output: 

How to run external commands using exec package?

0

1 Answer 1

3

Couple of issues:

  • In exec.Command(path, " -l ."), the arguments should be separate strings, not a single string.
  • (nit) The ls command path is logged as "pwd" which is not congruent with the output you mentioned you were getting in the question.

Try this:

package main

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

func main() {
    path, err := exec.LookPath("ls")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("ls can be found at path: %s \n", path)

    cmd := exec.Command(path, "-l", ".")
    var out bytes.Buffer
    cmd.Stdout = &out

    err = cmd.Run()
    if err != nil {
        log.Println("after running external command: ", err)
    }

    log.Println("buffer output:", out.String())
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.