bash directory shortcuts

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"

You could write a wrapper function for cd and call it "cd" (ultimately the function will call builtin cd - using the builtin keyword). You could use a prefix character that Bash won't expand on the command line before your function sees it and that's unlikely to appear as the initial character in your directory names, perhaps ":". You would want to make it more robust, but here's a simple outline:

# format: [semicolon] shortcut colon destination [semicolon] ...
export CDDATA='foo:/path/to/foo;bar:/path/to/bar;baz:/path/to/baz'

cd () {
    local dest=$1
    if [[ $dest == :* ]]
    then
        [[ $CDDATA =~ (^|;)${dest:1}:([^;]*)(;|$) ]]
        dest=${BASH_REMATCH[2]}
    fi
    if [[ -z $dest ]]
    then
        cd
    else
        builtin cd "$dest"
    fi
}

cd :bar    # pwd is now /path/to/bar

with bash:

~foo is reserved for the home directory of the user foo. I would not recommend creating users just for that convenience.

You can make your life easier (or harder) when changing directories by setting the CDPATH environment variable (look it up in bash(1)).

Apart from that, the only way to think of would be to set environment variables for those directories you want to abbreviate.

$ FOODIR=/var/lib/misc
$ cp ~/bar.txt $FOODIR

Tags:

Bash