Shell Scripting Utilities

up - Navigate up the path

This shell function makes it easy to chdir to a directory up in your path. It is mostly intended for interactive use and can be called in two ways:

  1. Using a single (non-zero) digit as argument
  2. Using any other string as argument
In the first case, it changes that many level up in your path. Example:
        cd /mntx/a/b/c/d/e
        up 3
will chdir you to /mntx/a/b. In the second case, it goes up directory by directory, until one is found which contains the argument as a substring. Example:
        cd /home/kasimir/projects/project_a/trunk/lib/fileutils
        up ject
will chdir to /home/kasimir/projects/project_a. If no argument is supplied, 1 is assumed, i.e. up behaves like cd .. .

Installation: The function has been tested with zsh version 4.3.9 and bash 3.2.48. Just paste it into your .zshrc or .bashrc respectively:

# up [NONZERODIGIT|STRING]
# Does a chdir upwards in current path.
# If the argument is a non-zero digit n, goes up n levels.
# Otherwise, goes up to the next directory whih contains the argument as
# sustring.
# If no argument is supplied, goes up one level (i.e. cd ..)
# Note that OLDPWD is preserved, i.e. after an
#    up XXX
# you can get to the previous directory by
#    cd -
up () {
    where_to=${1:-1}
    if [[ $where_to == *[1-9]* ]]
    then
        cd $(printf ../%.0s {1..$where_to})
    else
        local _nwd=$PWD # Where we will go to
        while [[ "$_nwd" != "" ]]
        do
            _nwd=${_nwd%/*} # Drop basename
            # See whether the new basename contains the target string
            if [[ "${_nwd##*/}" == *${where_to}* ]]
            then
                break
            fi
        done
        if [[ "$_nwd" == '' ]]
        then
            echo "No directory containing $where_to in path"
            return 1
        else
            cd "$_nwd"
        fi
    fi
}