June 18, 2009

bash: small improvement for the "cd" builtin

If you use the shell and walk around in directories wouldn’t it be cool to have “cd …” to move 2 levels up, “cd ….” to move 3 levels up …? I’m not sure if there’s an easier way to resolve it but the following lines work pretty nice so far and they just made it into my default .bashrc :P

cd() {
    if [[ "$1" =~ ^\.\.\.+$  ]]; then
        cd `echo "$1" | sed 's/\./..\//g' | sed 's/^\.\.\///g'`
    else
        builtin cd "$1"
    fi
}

For different older shell/bash versions you might need quotes around the regex.

Btw O’Reilly’s “Learning the Bash” is available within Google Books

Edit: another very important bookmark for bashscripting is the Advanced Bash-Scripting Guide

© tolleiv 2016 - CC BY-SA 3.0 - Powered by Hugo