0
1

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でコマンドラインツールを作った時のUnix wildcardの話

Last updated at Posted at 2018-05-25
Page 1 of 18

はじめに

Go(Un)Conference(Goあんこ)LT大会 2kgでLTしようと思ったけど、急用が入ったので資料だけ公開しておきます。(初Qiitaスライド)


Who


テキストを等分割するツール

https://github.com/sssinsi/gohs
読み方:ごす(呉須)

https://www.google.co.jp/search?&q=呉須


なぜ作ったか

Goツールの手始めに、簡単に作れるコマンドラインツールで勉強してみた。
(とりあえず手を動かして何かを作りたかった感)


こんな感じで分割してくれる

$cat a.file
1
2
3
4
5

$gohs -p a.file -c 3 -s=************
1
2
3
************
4
5

flag

コマンドラインツールを作る時よく使うflag
簡単。
https://github.com/golang/go/blob/master/src/flag/flag.go


flagの使い方

オプションは-flag=x or -flag xのように指定できる。

$gohs -p sample.txt -c 3 -s=************
1
2
3
************
4
5

当然こんな使い方もできるよね

$gohs -p sample.txt -c 3 -s ************
1
2
3
README.md
4
5

ファッ!?!?


突然のREADME.md


原因

cmd -x *
where * is a Unix shell wildcard, ....


wildcard?


ワイルドカード

$ls
README.md	main.go		sample.txt
$ls *
README.md	main.go		sample.txt
$ls s*
sample.txt

そうだよね


確認

flag.parseOne()のソースコードを読んでもどこでファイル名になっているのかわからず、試しにfmt.Println(os.Args)main.goの先頭に仕込んで、コマンド実行。

$go run main.go -p sample.txt -c 3 -s *
[/var/folders/mp/cmn3_f0s5fgd6wns0ng1tfrh0000gq
/T/go-build082551061/command-line-arguments
/_obj/exe/main -p sample.txt -c 3 
-s README.md main.go sample.txt]
...

つまり

flag.Parse()する以前に、オプションにカレントディレクトリのファイル一覧が指定されているため、最初のREADME.mdというファイル名を文字列として処理していた。

-s README.md main.go sample.txt

なるほどね


対策

*を文字列として使う場合は、=を使うか"で囲むと吉。

$gohs -p sample.txt -c 3 -s=************
$gohs -p sample.txt -c 3 -s "************"

過去を辿ってみたら

2017/12にwildcardのコメントが追加されてた、意外に最近。


ありがとうございました。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?