22

In Bash, how could I create a directory named -p?

mkdir -p failed.
mkdir "-p" failed.
mkdir "\-p" failed.
mkdir \-p failed.

Oliver Salzburg
  • 86,445
  • 63
  • 260
  • 306
Jichao
  • 7,145
  • 12
  • 52
  • 62
  • 1
    Note that all of these are attempting to escape the parameter for bash. Since it's the same escaped as not escaped, all of these except the third will just send the string "-p" to mkdir, which will parse it as an option. The option parsing isn't done in bash, so any way around this (described in the answers below) is a feature of mkdir (or rather, a lack of bug). – Score_Under Apr 07 '14 at 11:40
  • 11
    Gotta ask why you'd want such a directory. It would be a PITA to use. – Daniel R Hicks Apr 07 '14 at 11:44
  • 3
    @DanielRHicks: I created this folder by mistake, but do not know how to delete it. – Jichao Apr 07 '14 at 14:19
  • 4
    Shouldn't, then, the question be "How to delete a directory named '-p' under Linux with Bash"? – chepner Apr 07 '14 at 16:15
  • @chepner: Because they are same problems actually. I tried to delete the directory with `rmdir` but failed with same errors. – Jichao Apr 07 '14 at 16:41

2 Answers2

40

Most utilities (all POSIX compliant ones except for test and echo) support an "end of options" option --, so you could run:

mkdir -- -p

This is especially useful when renaming or removing files that could potentially start with a dash. In scripts you should always use

mv -- "$filename"

instead of a plain mv "$filename" or, even worse, an unquoted filename.

slhck
  • 223,558
  • 70
  • 607
  • 592
18

mkdir ./-p

Keep in mind that most other programs would need to use the same "trick".

Daniel B
  • 60,360
  • 9
  • 122
  • 163