How to open a Directory or a file starting with a "-", hyphen

Those of you who have not been in such a situation would never know how it feels when you are stuck opening/deleting a file or directory. The more you have been working on the shell, the more it sucks. When I tried all I could to get it work and still ended up with the same error all the time, I just sat on my chair, staring at the monitor for a while, wondering if this is somekind of bash's loophole :P.

I was trying to grep through some pidgin facebook chats when I was stuck for a while trying to open a directory with the name starting with a hyphen("-"). I tried all I could think of, but I always ended with the same error.

[shredder12]$ cd -directory
bash: cd: -d: invalid option
cd: usage: cd [-L|-P] [dir]

[shredder12]$ cd \-directory

[shredder12]$ cd *directory

[shredder12]$ cd "-directory"

As you can see the trouble is that the alphabets after a "-", hyphen, are being considered as the command attributes/options but they are not, so what we need here is:

  • a way to tell the command that its not an option
  • or, make the command start with something other than a hyphen

The first method is to use a double-dash "--" before the name. A double-dash means the end of options to that command.

[shredder12]$ cp -- -directory/

For the other way, we need to start the command with something other than a hyphen and still make sure that its the same file.

[shredder12]$ cp ./-directory

3 Comments

September 8th, 2010 09:39 am
Many thanks shredder12. Even though i have like 5 years using a lot the shell i never had to get to a problem that started with the hyphen. My first logical guess would have been the double quotes and after that your second solution. But the first one i understand it after reading this. Nice work.
September 12th, 2010 04:19 am

Hi Luis. I don't know why I didn't get the second one, may be I lost all hope after failing the first three ;).

Luis Rios (not verified)
November 7th, 2010 12:58 am
Try cd ./-directory or go to the parent directory and try cd [parent directory]/-directory both worked in my case.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <p> <br>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.
  • Search Engines will index and follow ONLY links to allowed domains.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.