ハイフンで始まる名前のファイルを消す

先日ちょっとした拍子で意図せずハイフンから始まる名前のファイルを作ってしまった.

$ ls
-q  hoge.cpp  test/

"-q"ってどういうファイルだよ….

早速rmで消そうとしたのだけど,以下のようにエラーが出てうまくいかない.

$ rm -q
rm: illegal option -- q
usage: rm [-f | -i] [-dPRrvW] file ...
       unlink file

どうやら"-q"がrmコマンドのオプションとして扱われてしまっているみたい.


どうしたものかと思ってman rmで調べてみたところ,以下の記述を見つけた.

The rm command uses getopt(3) to parse its arguments, which allows it to accept the `--' option which will cause it to stop processing flag options at that point. This will allow the removal of file names that begin with a dash (`-'). For example:

  rm -- -filename

The same behavior can be obtained by using an absolute or relative path reference. For example:

  rm /home/user/-filename
  rm ./-filename

どうやらコマンドの後にハイフンをふたつ("--")書けば,それ以降の引数はオプションとして扱われなくなるらしい.という訳で以下のようにしてファイルを削除することができた.

$ rm -- -q

絶対/相対パスでファイル名を指定しても同様に削除することができた.

$ rm ./-q


前者の方法はgetoptを使って引数をparseしているコマンドでしか使えないので,後者の方法で覚えた方がいいかもしれない.