Linux – Change directory upwards to specified goal

bashfile managementlinux

I'm often deep inside a directory tree, moving upwards and downwards to perform various tasks. Is there anything more efficient than going 'cd ../../../..'?

I was thinking something along the lines of this: If I'm in /foo/bar/baz/qux/quux/corge/grault and want to go to /foo/bar/baz, I want to do something like 'cdto baz'. I can write some bash script for this, but I'd first like to know if it already exists in some form.

Best Answer

Here's a function that does what you want:

cdto () { cd "${PWD%/$1/*}/$1"; }

Here's another handy one:

c2 () {
        local path num
    if (($# != 0))
    then
        path='./'
    fi
    if [[ -z ${1//.} ]]
    then
        num=${#1}
    elif [[ -z ${1//[[:digit:]]} ]]
    then
        num=$1
    else
        echo "Invalid argument"
        return 1
    fi
    for ((i=0; i<num-1; i++))
    do
        path+='../'
    done
    cd $path
}

Usage:

c2 .    # same as cd .
c2 ..   # same as cd ..
c2 ...  # same as cd ../..
c2 3    # also same as cd ../..
c2      # same as cd (which is the same as cd ~)

I thought one of the shells used to have the cumulative dot-dot-dot feature (I even checked Vista just now and it didn't have it although Google claims that some versions of Windows do).

Edit

An undocumented feature of Bash is that a lot of characters are acceptable in function names. As a result, you can do this:

.. () { cd ..; }
... () { cd ../..; }
.... () { cd ../../..; }
..... () { cd ../../../..; }
Related Question