Your program is not exiting because of command error.
It is exiting because you put log.Fatal(err)
.
log.Fatal
exits the program with SIGINT 1, if you just want to log the error, do log.Println(err)
. See the doc here: https://golang.org/pkg/log/#Logger.Fatal
Also, to do it the goway, you should bubble up the error and let the caller of the function handle the error.
Now, regarding what you want to do, I suggest to use the function LookPath
of the exec
package, it does exactly what you want by searching for an executable with the given name in your path. Here is the doc: https://golang.org/pkg/os/exec/#LookPath
You could do something like that:
package main
import (
"flag"
"fmt"
"log"
"os/exec"
)
var pkg = flag.String("pkg", "", "package name")
func main() {
flag.Parse()
if !PackageInstalled(*pkg) {
if err := InstallPackage(*pkg); err != nil {
log.Fatal(err)
}
fmt.Printf("Package %s installed\n", *pkg)
return
}
fmt.Printf("Package %s already installed\n", *pkg)
}
func PackageInstalled(pkg string) bool {
_, err := exec.LookPath(pkg)
// check error
if err != nil {
// the executable is not found, return false
if execErr, ok := err.(*exec.Error); ok && execErr.Err == exec.ErrNotFound {
return false
}
// another kind of error happened, let's log and exit
log.Fatal(err)
}
return true
}
func InstallPackage(pkg string) error {
// install your package
// ...
return nil
}
and run it this way go run main.go -pkg yum