The Bash command
cd -
prints the previously used directory and changes to it.
On the other hand, the Bash command
cd ~-
directly changes to the previously used directory, without echoing anything.
Is that the only difference? What is the use case for each of the commands?
Best Answer
There are two things at play here. First, the
-
alone is expanded to your previous directory. This is explained in thecd
section ofman bash
(emphasis mine):So, a simple
cd -
will move you back to your previous directory and print the directory's name out. The other command is documented in the "Tilde Expansion" section:This might be easier to understand with an example:
So, in general, the
-
means "the previous directory". That's whycd -
by itself will move you back to wherever you were.The main difference is that
cd -
is specific to thecd
builtin. If you try toecho -
it will just print a-
. The~-
is part of the tilde expansion functionality and behaves similarly to a variable. That's why you canecho ~-
and get something meaningful. You can also use it incd ~-
but you could just as well use it in any other command. For examplecp ~-/* .
which would be equivalent tocp "$OLDPWD"/* .