search
LoginSignup
8

More than 5 years have passed since last update.

posted at

Organization

Go言語でコマンドが実行可能かチェックする

os/exec.LookPathを使うと、コマンドが実行可能かチェックできる。$PATH を考慮して探してくれるが、スラッシュが入っていると $PATH を考慮しない。

package main

import (
    "log"
    "os/exec"
)

func main() {
    tests := []string{
        "hoge",
        "/bin/hoge",
        "./hoge",
    }

    for _, test := range(tests) {
        if _, err := exec.LookPath(test); err != nil {
            log.Print(err)
        }
    }
}

実行結果

2013/12/10 19:18:34 exec: "hoge": executable file not found in $PATH
2013/12/10 19:18:34 exec: "/bin/hoge": stat /bin/hoge: no such file or directory
2013/12/10 19:18:34 exec: "./hoge": stat ./hoge: no such file or directory

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
8