9

I have the following situation:

$ ls
0.txt  aaa.txt  a-.txt  a.txt  b.txt  ddd.txt  -hello.txt  libs  -.txt  ,.txt  !.txt  ].txt  \.txt
$ ls [-a]*.txt
ls: opzione non valida -- "e"
Try 'ls --help' for more information.
$ ls [a-]*.txt
ls: opzione non valida -- "e"
Try 'ls --help' for more information.

The dash (-) creates some problems. How can I find a file starting with -?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
zer0uno
  • 1,273
  • 4
  • 16
  • 15

1 Answers1

20

Use -- to indicate end of options for ls:

ls -- -*

or do the following to explicitly indicate the argument on current directory with ./

ls ./-*

If you want to input more options for ls, put them before -- or ./ e.g.

ls -l -- -*
ls -l ./-*
heemayl
  • 54,820
  • 8
  • 124
  • 141
  • forget --, use ./, as it is more portable – Olivier Dulac Oct 01 '16 at 23:08
  • 3
    @OlivierDulac Unless you're working with 1970s (1980s?) systems, no, `--` is portable. – Gilles 'SO- stop being evil' Oct 01 '16 at 23:50
  • 3
    Do we really not have a canonical "how do I escape `-`" question I can flag this as a duplicate of? It seems like we have had one of these questions every week for a while – cat Oct 02 '16 at 01:39
  • @Gilles: well, the added advantage of going the "./" route is that you don't have to 1) ensure *all* the command you use know about "--" 2) same for any possible function of the same name ... I keep using that way. But one still needs to **also** use the '--' in one's function to clearly mark the end of options, ensuring a parameter won't affect the function's behaviour. ie, we need both: `something ./*` on the command line, to properly designate the files we want to affect, and `somecommand [options here] -- "$@"` in our function definitions, where -- clearly delimitate options from args – Olivier Dulac Oct 03 '16 at 15:52
  • And I did encounter commands ignoring what "--" was meant to be, but I'll have to research about those at work, as I can't remember which command it was (an ancient aix tar, maybe?) – Olivier Dulac Oct 03 '16 at 15:54
  • If you're doing this in a shell script, [shellcheck](https://github.com/koalaman/shellcheck) will actually warn you that this is a possibility – Ben Oct 06 '16 at 21:56