Russian and French Bullets Collide
It’s like finding a needle in a haystack, and stuck in its eye is another needle.
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.



