Execute Commands

Simple script to learn how to execute commands and re-use later on future programs.

package main

// usage: go run execmd.go -cmd <command>
// how to execute commands on a system (windows or linux)

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

func executeCommand(command string, argsArray []string) (err error) {
	args := argsArray
	// create object
	cmdObj := exec.Command(command, args...)
	// stdout to display the output on the screen
	cmdObj.Stdout = os.Stdout
	// process errors
	cmdObj.Stderr = os.Stderr
	// run the command
	err = cmdObj.Run()

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

func main() {
	cmd := flag.String("cmd", "", "Select command to use")
	flag.Parse()
	command := "sudo"
	executeCommand(command, []string{*cmd})

}

To learn: How to parse more than one argument on the same flag

Last updated