8

I tried to cd into a directory named - that I created for experimenting. I could not from Bash. How do I cd into it?

With Nautilus on Ubuntu 13.10 I could easily do this, and even create files inside it effortlessly. I did a Google search and here is what I got. That covers the case when directories begin with a -, like -test, but not the case when the entire name is one single -. Even rm does not work, although I was able to delete it from Nautilus.

cat test.txt >- copies text from test.txt into a file named -, but cat - >test2.txt does what it would do in normal circumstances, that is, copy input from stdin into test2.txt, not from the file -.

Why does Nautilus have no problem with this but bash does?

1 Answers1

16

Use:

cd ./-

Or:

cd /absolute/path/leading/to/-

Or, better:

mv ./- something-sensible
cd something-sensible

The lone dash is used by a lot of commands to mean 'standard input' or 'standard output'. A few commands can be persuaded to take one lone dash to standard input and another to mean standard output in a single command invocation: for example, with GNU Tar, tar -cf - -T - reads the list of file names to archive from standard input (-T -), and writes the tar file to standard output (-f -). Such commands never check to see if there is a real file called -; they just compare the name with - and treat it as the appropriate standard I/O stream. You work around the problem the same way: use a name such as ./- to specify the file.

You might also note that a name -- (double dash) also cause problems because the double dash argument is used to separate options from the file name (non-option) arguments, as in:

rm -fr -- -

This would remove the file or directory -, but would leave the file (or directory) -- unchanged. Study the specification of the POSIX Utility Conventions to see where this behaviour is defined.

  • 3
    The last choice is the best one (+1). :) –  Dec 30 '13 at 03:59
  • 1
    In most systems cd - means cd to the last directory you were in. So don't name directories -; or ~, or /, or ., or .. –  Dec 30 '13 at 04:13
  • Thank you for the answer. However, one would still expect cd "-" to work, but it does not. –  Dec 30 '13 at 04:14
  • 3
    Using - as a directory name in the cd command is specified by POSIX to be equivalent to: cd "$OLDPWD" && pwd. So it does work, just not as you are expecting it to; it returns you to your last working directory. – Michael Burr Dec 30 '13 at 04:16
  • 4
    @AnkitPati Quoting doesn't help, because they hyphen has no special meaning to the shell parser; it's the cd command that assigns it a special meaning. – chepner Dec 30 '13 at 14:29