Linux commands in Golang can be executed using the Command() function in the os/exec package.
func Command(name string, arg ...string) *Cmd
name: This is the name of the program to run.arg: These are the arguments to pass to the program.package mainimport ("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")}
fmt and os/exec packages.execute() function, which takes a Linux command, executes the command, and prints the output.execute() function with "df" as argument to execute the df command.execute() function with "ls" as argument to execute the ls command.package mainimport ("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")}
fmt and os/exec packages.execute() function, which takes a Linux command and the arguments to pass to the command, executes the command, and prints the output.execute() function with "df" and "-a" as arguments to execute the df command.execute() function with "ls" and "-l" as arguments to execute the ls command.Free Resources