Skip to content

Instantly share code, notes, and snippets.

@westonruter
Created August 5, 2011 21:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonruter/1128549 to your computer and use it in GitHub Desktop.
Save westonruter/1128549 to your computer and use it in GitHub Desktop.
Bash shortcut function to cd you to an ancestor directory, named as first argument. Stop having to cd ../../../..
#!/bin/bash
# Usage: cdup [DIRNAME]
# Bash shortcut function to cd you to ancestor directory named as first argument.
# If DIRNAME is not supplied, then .. is used.
# Stop having to cd ../../../..
# Use `cd -` to undo, to restore old working directory.
# Use aliases for common directories, like: alias docroot="cdup docroot".
# Add function to your ~/.profile
#
# Example:
# $ pwd
# > /var/www/html/example.com/docroot/long/path/to/something
# $ cdup html
# $ pwd
# > /var/www/html
# $ cd -
# $ pwd
# > /var/www/html/example.com/docroot/long/path/to/something
function cdup {
if [ $# == 0 ]; then
cd ..
return 0
fi
dir="$1"
old=`pwd`
new=`sed s:/$dir/.*:/$dir: <<< $old`
if [ "$old" == "$new" ]; then
echo "Can't find '$dir' among ancestor directories." 1>&2
return 1
fi
cd $new
}
@lurch
Copy link

lurch commented Aug 27, 2011

Nice script! I recently wrote a "cdnew" function to combine a "cd" with a "mkdir -p", and "cdtemp" which combines "cd" and "mktemp -d"

I think line 28 above needs to instead be:
new=sed s:/$dir/.*:/$dir: <<< old``
though, so that when you have a path like
/tmp/testfoo/test/foo/long/path
then when you do
`cdup foo`
it works as you'd expect it to ;)

@westonruter
Copy link
Author

@lurch: Thanks! I made the tweak. I also realized an improvement would be to use "aunt" and "uncle" directories in addition to direct ancestors. For example say we have the following directory structure:

docroot/life/mammal/feline/lion/
scripts/
tests/
library/mylib

If you were inside of docroot/life/mammal/feline/lion/, you could run:

cdup scripts
cdup mylib

and it would take you to the expected directories, by walking up the the ancestor tree and at each level looking at siblings and so on.

@lurch
Copy link

lurch commented Aug 28, 2011

@westonruter: Not so sure about the 'aunt / uncle' version being added to cdup - makes it much less of a "single shot" command. IMHO of course ;)

@westonruter
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment