Bash – Directory Shortcuts

bash

When I type cd ~foo, I'd like bash to take me to some directory foo as a shortcut for typing the full directory path of foo. and I'd like to be able to cp ~foo/bar.txt ~/bar.txt to copy a file from the /foo/ directory to the home directory… So basically, I want something that works exactly like ~/ does, but where I specify what the directory should be. [I'm sure I should jfgi, but I don't know what to fg]

Best Answer

The way I used to do this is to create a directory that contains symlinks to the directories you want shortcuts do, and add that directory to your CDPATH. CDPATH controls where cd will search when you switch directories, so if that directory of symlinks is in your CDPATH you can cd to any of the symlinked directories instantly:

mkdir ~/symlinks
ln -s /usr/bin ~/symlinks/b
export CDPATH=~/symlinks
cd b   # Switches to /usr/bin

The downside of course is it won't work if there's a directory in your current directory named "b" -- that takes precedence over the CDPATH


I normally dislike answers that say "first you need to switch shells", but this exact feature exists in ZSH, if you're willing to use that instead; it's called named directories. You export a variable foo, and when you refer to ~foo it resolves to the value of $foo. This is especially convenient because it works in commands besides cd:

echo hi > /tmp/test
export t=/tmp
cat ~t/test   # Outputs "hi"