34
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-04-28

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

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))
}
34
41
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
34
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?