Shell variable ~-

After writing the previous post, I poked around in the bash shell documentation and found a handy feature I’d never seen before, the shortcut ~-.

I frequently use the command cd - to return to the previous working directory, but didn’t know about ~- as a shotrcut for the shell variable $OLDPWD which contains the name of the previous working directory.

Here’s how I will be using this feature now that I know about it. Fairly often I work in two directories, and moving back and forth between them using cd -, and need to compare files in the two locations. If I have files in both directories with the same name, say notes.org, I can diff them by running

    diff notes.org ~-/notes.org

I was curious why I’d never run into ~- before. Maybe it’s a relatively recent bash feature? No, it’s been there since bash was released in 1989. The feature was part of C shell before that, though not part of Bourne shell.

3 thoughts on “Shell variable ~-

  1. Personally I find it difficult to remember clever syntactical short cuts. This has been the plague in languages like C++ (3-way compare anyone). I’ll stick to a few extra letters so I don’t have to remember stuff like this which also means an extra layer of confusion when reading scripts. FWIW I never liked tail fins on cars either

  2. Going further down the rabbit hole, pushd, popd, and dirs are handy for having multiple directories in a stack, and switching between them. I have dirs formatted as a multiline output in my prompt, so I can always see the stack, and pushd +1 to cycle through them for instance.

Comments are closed.