Bash – cd to previous directory without echo of directory name

bashcd-command

This answer gave me cd - as shorthand to change to my previous directory in Bash. It does have a major problem: it prints the directory it changes to, wasting my screen space, as that directory is then repeated in the prompt on the next line.

I know I can do cd $OLDPWD, also mentioned in that answer, and cd - >/dev/null but that is much more typing.

In the bash man page it says:

… or if – is the first argument, and the directory change is successful, the absolute path name of the new working directory is written to the standard output.

How can I make - not to be the first argument? By using any of the cd optional arguments? Any other way to suppress the echo or minimise typing without the need for defining functions/aliases on every machine I work with?

Best Answer

cd only takes the first argument into account, ignoring all others. None of the options influence the echo of the previous pathname (maybe the documented -@ does have that effect, but that is an invalid option on my system).

If you don't want to use an alias/function, which could give you even less characters to type than cd -, or redirect to /dev/null, my suggestion is to start using the special tilde expansion in bash:

cd ~-

From bash man page:

If the tilde-prefix is a `~-', the value of the shell variable OLDPWD, if it is set, is substituted.

This seems to be yet another area in bash where some special meaning was created. Tilde expansion normally works on the $DIRSTACK, manipulated/investigated by pushd, popd, and dirs, it can be used in other commands as well (cp ~-/somefile .) and if you have used pushd you can use ~N (where N is a number of levels pushed back) to get to these directories (for cd or other commands).


BTW if you have accounts on multiple machines and assuming you use ssh to login to them from one place, you should consider adding to your ~/.bashrc:

if [ -f ~/.bash_common ]; then
    . ~/.bash_common
fi

and then have script on your work machine that uses scp to "push" bash_common to each of those machines. That way you can add and share common functionality over multiple machines with minimal overhead.

Related Question