LoginSignup
15
8

More than 5 years have passed since last update.

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

Posted at

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
15
8
0

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
  3. You can use dark theme
What you can do with signing up
15
8