Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

Go exec command

Posted on January 17, 2024January 18, 2024 By nim No Comments on Go exec command

Copy from: https://zetcode.com/golang/exec-command/

Go exec command tutorial shows how to execute shell commands and programs in Golang.

The Run function starts the specified command and waits for it to complete, while the Start starts the specified command but does not wait for it to complete; we need to use Wait with Start.

Contents

Toggle
  • Go os/exec
  • Go exec program
  • Go exec.Command
  • Go exec command with multiple args
  • Go exec command capture output
  • Go cmd.StdinPipe
  • Go cmd.StdoutPipe

Go os/exec

The os/exec package runs external commands. It wraps os.StartProcess to make it easier to remap stdin and stdout, connect I/O with pipes, and do other adjustments.$ go version go version go1.18.1 linux/amd64

We use Go version 1.18.

Go exec program

The Run starts the specified command and waits for it to complete.

package main

import (
    "log"
    "os/exec"
)

func main() {

    cmd := exec.Command("firefox")

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}

In the code example, we execute the Firefox browser.

Go exec.Command

The Command returns the Cmd struct to execute the specified program with the given arguments. The first parameter is the program to be run; the other arguments are parameters to the program.

package main

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

func main() {
    cmd := exec.Command("tr", "a-z", "A-Z")

    cmd.Stdin = strings.NewReader("and old falcon")

    var out bytes.Buffer
    cmd.Stdout = &out

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("translated phrase: %q\n", out.String())
}

In the code example, we transform the input via the tr command.cmd := exec.Command(“tr”, “a-z”, “A-Z”)

The tr standard Linux command translates, squeezes, and/or deletes characters from standard input, writing to standard output. In our case, we transform lowercase letters to uppercase ones.cmd.Stdin = strings.NewReader(“and old falcon”)

Through the Stdin field, we pass a string to the command as its input.var out bytes.Buffer cmd.Stdout = &out

The output of the program will be written to the bytes buffer.$ go run command.go translated phrase: “AND OLD FALCON”

Go exec command with multiple args

We can pass multiple arguments to the exec.Command.

package main

import (
    "fmt"
    "os/exec"
)

func main() {

    prg := "echo"

    arg1 := "there"
    arg2 := "are three"
    arg3 := "falcons"

    cmd := exec.Command(prg, arg1, arg2, arg3)
    stdout, err := cmd.Output()

    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Print(string(stdout))
}

The example runs the echo command with three arguments.$ go run multiple_args.go there are three falcons

Go exec command capture output

The Output runs the command and returns its standard output.

package main

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

func main() {

    out, err := exec.Command("ls", "-l").Output()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(out))
}

The example captures the output of the ls command and prints it.

Go cmd.StdinPipe

The pipe allows us to send the output of one command to another. The StdinPipe returns a pipe that will be connected to the command’s standard input when the command starts.

package main

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

func main() {

    cmd := exec.Command("cat")
    stdin, err := cmd.StdinPipe()
    if err != nil {
        log.Fatal(err)
    }

    go func() {
        defer stdin.Close()
        io.WriteString(stdin, "an old falcon")
    }()

    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s\n", out)
}

In the code example, we write a string to the standard input inside a goroutine.cmd := exec.Command(“cat”)

The cat command concatenates the given files to the standard output. When no file is given, or with -, the command reads standard input and prints it to standard output.stdin, err := cmd.StdinPipe()

We get the standard input pipe of the cat command.go func() { defer stdin.Close() io.WriteString(stdin, “an old falcon”) }()

Inside the goroutine, we write a string to the stdin pipe.$ go run stdinpipe.go an old falcon

Go cmd.StdoutPipe

The StdoutPipe returns a pipe that will be connected to the command’s standard output when the command starts.

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os/exec"
    "strings"
)

func upper(data string) string {

    return strings.ToUpper(data)
}

func main() {
    cmd := exec.Command("echo", "an old falcon")

    stdout, err := cmd.StdoutPipe()

    if err != nil {
        log.Fatal(err)
    }

    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }

    data, err := ioutil.ReadAll(stdout)

    if err != nil {
        log.Fatal(err)
    }

    if err := cmd.Wait(); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s\n", upper(string(data)))
}

The example reads the output of the echo command through the pipe and transforms it into uppercase letters.cmd := exec.Command(“echo”, “an old falcon”)

The command to run is the echo command with a single string argument.stdout, err := cmd.StdoutPipe()

We get the standard output pipe.if err := cmd.Start(); err != nil { log.Fatal(err) }

The command is executed with the Start function; it does not wait wait for it to complete.data, err := ioutil.ReadAll(stdout)

We read the data from the pipe.if err := cmd.Wait(); err != nil { log.Fatal(err) }

The Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete. It closes the pipe after seeing the command exit.$ go run stdoutpipe.go AN OLD FALCON

In this article we have executed external commands in Golang.

Golang

Post navigation

Previous Post: [Golang] Generate the Binary Files on Multi Architecture by Github Action
Next Post: [Golang] Approach Channel in Calling another function with Golang

More Related Articles

[Golang] Validate trong golang và echo framework. Golang
[Golang] Looking filepath.Walk to return any file and children folder in the folder Golang
[Golang/string] Remove or Delete a few words or characters in a string through Golang. Golang
[issue/alpine] docker 20.10.2 -> golang:1-alpine3.14 error: make: go: Operation not permitted Docker
[Golang] List large files in the folder quickly on Golang Golang
[Golang] How use Ramdom in Golang Golang

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.