Bash – How to Enter a Directory Named Only a Minus

bashcd-command

I downloaded lessn to my webserver and unzipped it.

It contains a folder named -. I assumed I know how to deal with that, but I don't.

I tried cd -- -, but that doesn't have the desired effect. Using quotes doesn't seem to affect it either. I put slashes all over the place, to no avail.

What's the proper way to change into this folder?

Best Answer

You want to avoid it from being a parameter, thus we try to prepend something to it. The current directory can be accessed with ., thus the subfolder - can be accessed alternatively with ./-.

cd ./-

The reason that cd -- - doesn't work is because this is implemented differently if you compare rm (see man rm) to cd (see man bash or man cd), cd has a different interpretation which sees - as a parameter (see man bash or man cd).

It should also be noted that cd is a shell builtin function, as can be read in this answer:

cd is not an external command - it is a shell builtin function. It runs in the context of the current shell, and not, as external commands do, in a fork/exec'd context as a separate process.

There is an external cd command, but it does something entirely different.

This explains why the implementation is different, as Bash and Coreutils are two different things.

Let's just suppose you wouldn't believe this, how do we confirm that? Use which and type.

 $ which cd && type cd
which: no cd in (/usr/local/bin:/usr/bin:/bin:/opt/bin:/usr/x86_64-pc-linux-gnu/gcc-bin/4.7.2:/usr/games/bin
cd is a shell builtin
 $ which rm && type rm
/bin/rm
/bin/rm is /bin/rm

See man which for more information, and man bash or man type for type

Related Question