Created
August 5, 2011 21:17
-
-
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 ../../../..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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: 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.
@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 ;)
FYI: Latest is going to go here: https://github.com/westonruter/misc-cli-tools/blob/master/cdup
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ;)