Skip to content

Instantly share code, notes, and snippets.

@craSH
Created April 24, 2010 05:43
Show Gist options
  • Save craSH/377491 to your computer and use it in GitHub Desktop.
Save craSH/377491 to your computer and use it in GitHub Desktop.
cd to nearest matching parent directory (stuff in a .bashrc or source it)
function cdp() {
# cd to the nearest matching parent directory
# e.g. if PWD is /foo/bar/baz/alice/bob/eve, 'cdp baz' will cd to /foo/bar/baz/
shopt -q nocaseglob
nocaseglob=$?
shopt -s nocaseglob
pat="^(.+)$1[^/]*"
if [[ "$PWD" =~ $pat ]] ; then
newdir=${BASH_REMATCH[0]}
cd $newdir
echo $newdir
fi
if (( $nocaseglob == 1 )) ; then shopt -u nocaseglob; fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment