Bash – Conflict between `pushd .` and `cd -`

bashcd-commandpushdshell

I am a happy user of the cd - command to go to the previous directory. At the same time I like pushd . and popd.

However, when I want to remember the current working directory by means of pushd ., I lose the possibility to go to the previous directory by cd -. (As pushd . also performs cd .).

How can I use pushd to still be able to use cd -

By the way: GNU bash, version 4.1.7(1)

Best Answer

You can use something like this:

push() { 
    if [ "$1" = . ]; then
        old=$OLDPWD
        current=$PWD
        builtin pushd .
        cd "$old"
        cd "$current"
    else
        builtin pushd "$1"
    fi
}

If you name it pushd, then it will have precedence over the built-in as functions are evaluated before built-ins.

You need variables old and current as overwriting OLDPWD will make it lose its special meaning.

Related Question