I use "cd -" to switch between folders. like:

cd /etc/                                                                                                                          
cd -   

but why "cd -" will print the address(like pwd)? How can I stop it print the address?

migrated from stackoverflow.com Jan 19 '13 at 11:40

This question came from our site for professional and enthusiast programmers.


SUS4 says:

When a - is used as the operand, this shall be equivalent to the command:

    cd "$OLDPWD" && pwd

which changes to the previous working directory and then writes its name.

So, if you don't want the printing half of the behaviour, just do the first bit yourself:

cd "$OLDPWD"

Or the tilde expansion equivalent

cd ~-

Often if you need this, pushd / popd is a better albeit less portable choice.

  • 1
    +1, don't know why this was downvoted since it certainly explains why it does what it does. Adding the bit that shows how to fix it. – user53528 Jan 19 '13 at 5:39
  • Dunno. Also added ~-, pushd, popd – ormaaj Jan 19 '13 at 6:09

Just redirect the stdout to black hole like this

cd - > /dev/null
  • I don't like this, because it does double work: first is does a pwd which is than redirected to /dev/null. Why not just using cd $OLDPWD as ormaaj suggest? – Andreas Florath Jan 19 '13 at 10:12
  • Because it is more typing? And it uses some 'magic' environment variable? Granted, cd - is also a bit magical, but at the very least it is easier to remember. – JvO Jan 21 '13 at 0:52
  • This method is fine. It isn't "double work", it's just hiding output (the shell doesn't literally have to run through all the steps necessary to run two commands). You also have to hide output in a similar manner if using pushd/popd in a script. – ormaaj Jan 23 '13 at 4:00

The simplest way is not to use it. Run the commands in a separate shell:

(cd /etc/; ... )

This does not change the current working directory of the 'main' shell. This is typically more robust than using OLDPWD because you can have many cd commands here like

(cd /etc; ... ; cd /tmp; ... )
  • That has different semantics though (especially if ... changes the environment) and creates an extra process. – Mat Jan 19 '13 at 12:59
  • Different semantics to what? IMHO it is completely unclear, what happens between the cd /etc and the cd -. If there are environment changes, you are completely right. If there are additional cds than maybe this is the better way. – Andreas Florath Jan 19 '13 at 13:24
  • What I mean is that (cd /etc; FOO=bar) and cd /etc; FOO=bar; cd -; don't do the same thing. – Mat Jan 19 '13 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.