38
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

サクッとシェルスクリプトを書く代わりにGoを使う為の基本事項

コマンドライン引数の取得と要素数チェック

args.go
func main() {
    args := os.Args
    if len(args) <= 1 {
        log.Fatal("Usage: ", path.Base(args[0]), " anything")
    }

    fmt.Println("len: ", len(args), " values: ", args)
}

文字列 -> 数値変換

atoi.go
func main() {
    args := os.Args
    if len(args) != 2 {
        log.Fatal("Usage: ", path.Base(args[0]), " number")
    }
    if val, err := strconv.Atoi(args[1]); err != nil {
        log.Fatal(err)
    } else {
        fmt.Println("val: ", val)
    }
}

ファイル存在チェック

fileexists.go
func main() {
    args := os.Args
    if len(args) != 2 {
        log.Fatal("Usage: ", path.Base(args[0]), " filename")
    }
    if _, err := os.Stat(args[1]); err == nil {
        fmt.Println("File exists")
    } else {
        fmt.Println("File not found.")
    }
}

ディレクトリの中身一覧取得

dirs.go
func main() {
    args := os.Args
    if len(args) != 2 {
        log.Fatal("Usage: ", path.Base(args[0]), " dir")
    }
    files, _ := ioutil.ReadDir(args[1])
    for _, f := range files {
        fmt.Println(f.Name())
    }
}

ファイル読み込み

fileread.go
func main() {
    args := os.Args
    if len(args) != 2 {
        log.Fatal("Usage: ", path.Base(args[0]), " file")
    }
    data, err := ioutil.ReadFile(args[1])
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Read:[", string(data), "]")
}

ファイル書き込み

filewrite.go
func main() {
    args := os.Args
    if len(args) != 3 {
        log.Fatal("Usage: ", path.Base(args[0]), " filename text")
    }

    data := []byte(args[2])
    err := ioutil.WriteFile(args[1], data, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

現在時刻取得

* 引数の値はこのまま2006〜とすること。

now.go
func main() {
    now := time.Now()
    fmt.Println("now: ", now)
    fmt.Println("now: ", now.Format("20060102"))       // YYYYMMDD
    fmt.Println("now: ", now.Format("20060102150405")) //YYMMDDhhmmss
}

外部コマンド実行

exec.go
func main() {
    args := os.Args
    if len(args) < 2 {
        log.Fatal("Usage: ", path.Base(args[0]), " cmd")
    }
    out, err := exec.Command(args[1], args[2:]...).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Out: ", string(out))
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
38
Help us understand the problem. What are the problem?