使用Go检查是否已安装系统软件包并退出程序

Im trying to check if package is installed in system (Centos/Yum). Im trying to use for that exec.Command method:

func YumCheckIfPackageInstalled(pkg string) string {
    out,err := exec.Command("yum", "list", "installed", pkg).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Output %s
", out)

    return "string"
}

Problem is that when "pkg" is installed program is continuing to work, but if it is not it is exiting with:

exit status 1

How to prevent program to exit on os command error?

What i want to achieve is to check if some packages are installed and if not i want to install them. Maybe there is some better way to solve that problem than executing exec.Command-s?

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
", *pkg)
                return
        }
        fmt.Printf("Package %s already installed
", *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