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 ../../.. user@host:~/dir1/dir2$
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
fi
dir=`pwd`
while [ $dir != / ]; do
dir=`dirname "$dir"`
if [ `basename "$dir"` = "$1" ]; then
cd "$dir"
return 0
fi
done
return 1
}
Now I can search up by name:
user@host:~/dir1/dir2/dir3/dir4/dir5$ up dir2 user@host:~/dir1/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?
2. Lenny says:
The convention in file browsers is “up” to go to an ancestor in the file tree, “back” to an earlier view.
Comments on this entry are now closed. Thanks to those who participated. You can still email me.


