Lenny Domnitser’s

⇙ Jump to content


This is a static archive of the domnit.org blog,
which Lenny Domnitser wrote between 2006 and 2009.

Jump Up to an Ancestor Directory in Bash/sh

Unix shell nerdery ahead, general public ignore.

The project I’m working on has deeply nested directories, and I end up doing something like this:

user@host:~/dir1/dir2/dir3/dir4/dir5$ cd ../../..

Tired of counting or guessing how many directories up to go, I wrote a function in my .bashrc:

up() {
    if [ $# != 1 ]; then
        echo "usage: up NAME" >&2
        return 2
    while [ $dir != / ]; do
        dir=`dirname "$dir"`
        if [ `basename "$dir"` = "$1" ]; then
            cd "$dir"
            return 0
    return 1

Now I can search up by name:

user@host:~/dir1/dir2/dir3/dir4/dir5$ up dir2

A possible extension to this simple function would be to save the original directory in the environment and write a down function to search back down.

2 comments on Jump Up to an Ancestor Directory in Bash/sh

1. Alex says:

Why “jump up” when CD to ancestor? Is not “back” more appropriate?

—Alex, 12 March 2009, 13:16

2. Lenny says:

The convention in file browsers is “up” to go to an ancestor in the file tree, “back” to an earlier view.

—Lenny, 12 March 2009, 14:57

Comments on this entry are now closed. Thanks to those who participated. You can still email me.