How to execute Linux commands in Golang

Linux commands in Golang can be executed using the Command() function in the os/exec package.

Syntax

func Command(name string, arg ...string) *Cmd

Parameters

  • name: This is the name of the program to run.
  • arg: These are the arguments to pass to the program.

Code example 1: Command without arguments

package main
import (
"fmt"
"os/exec"
)
func execute(cmd string) {
out, err := exec.Command(cmd).Output()
if err != nil {
fmt.Printf("%s", err)
}
fmt.Println("Command Successfully Executed")
output := string(out[:])
fmt.Println(output)
}
func main() {
execute("df")
println("-----")
execute("ls")
}

Explanation

  • Lines 3–6: We import the fmt and os/exec packages.
  • Lines 8–19: We define the execute() function, which takes a Linux command, executes the command, and prints the output.
  • Line 22: We invoke the execute() function with "df" as argument to execute the df command.
  • Line 24: We invoke the execute() function with "ls" as argument to execute the ls command.

Code example 2: Command with arguments

package main
import (
"fmt"
"os/exec"
)
func execute(cmd string, args string) {
out, err := exec.Command(cmd, args).Output()
if err != nil {
fmt.Printf("%s", err)
}
fmt.Println("Command Successfully Executed")
output := string(out[:])
fmt.Println(output)
}
func main() {
execute("df", "-a")
println("-----")
execute("ls", "-l")
}

Explanation

  • Lines 3–6: We import the fmt and os/exec packages.
  • Lines 8–19: We define the execute() function, which takes a Linux command and the arguments to pass to the command, executes the command, and prints the output.
  • Line 22: We invoke the execute() function with "df" and "-a" as arguments to execute the df command.
  • Line 24: We invoke the execute() function with "ls" and "-l" as arguments to execute the ls command.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved