Skip to content

Instantly share code, notes, and snippets.

@falconindy
Last active September 19, 2018 19:56
Show Gist options
  • Save falconindy/0a5185ab9a8c34339d747d5dea59fb71 to your computer and use it in GitHub Desktop.
Save falconindy/0a5185ab9a8c34339d747d5dea59fb71 to your computer and use it in GitHub Desktop.
A shell function to cd to files/directories in your parent
up() {
local cdinto=0 x= traverse= curpath=
[[ $1 ]] || { cd ..; return; } # default to 1 level
[[ $1 = -d ]] && { cdinto=1; shift; }
for x; do
if [[ $x == +([[:digit:]]) ]]; then
(( x == 0 )) && return # noop
# build a path to avoid munging OLDPWD
while (( x-- )); do
traverse+=../
done
cd "$traverse"
else
curpath=$PWD
while [[ $curpath && ! -e $curpath/$x ]]; do
curpath=${curpath%/*}
done
if [[ $curpath ]]; then
if [[ $curpath != "$PWD" ]]; then
if (( cdinto )); then
cd "$curpath/$x"
else
cd "$curpath"
fi
fi
else
printf "error: failed to locate \`%s' in a parent directory\n" "$x"
return 1
fi
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment