Skip to content

Instantly share code, notes, and snippets.

@dmlittle
Created June 13, 2019 23:09
Show Gist options
  • Save dmlittle/5f0f00898fdf7f65686ae5f65fabf965 to your computer and use it in GitHub Desktop.
Save dmlittle/5f0f00898fdf7f65686ae5f65fabf965 to your computer and use it in GitHub Desktop.
goto shell function to easily navigate to different directories
# paths in which to find projects or directories
# top path wins
goto-refresh-search-paths () {
setopt nullglob
goto_search_paths=(
$GOPATH/src/*/*
~/Developer
)
unsetopt nullglob
}
goto-which () {
goto-refresh-search-paths
for p in $goto_search_paths; do
local it="$p/$1"
if [ -e "$it" ] ; then
echo "$it"
return 0
fi
done
echo "goto-which: not found: $1" > /dev/stderr
return 1
}
goto () {
local dir=$(goto-which "$1")
if [ -n "$dir" ]; then
echo "cd $dir"
cd "$dir"
else
echo "goto: not found: $1" > /dev/stderr
return 1
fi
}
_goto () {
goto-refresh-search-paths
COMPREPLY=()
# Only complete one word
if [[ $COMP_CWORD -gt 1 ]]; then
return 0
fi
# Complete with matching paths inside our search paths
local cur
cur="${COMP_WORDS[COMP_CWORD]}"
local path_glob
local candidates
for p in "${goto_search_paths[@]}"; do
# Loop through all the search paths and see if we can glob anything
# beginning with the user's typing.
path_glob="$p/$cur*"
candidates=($(compgen -G "$path_glob" | xargs basename))
# Add any matches to the completion result
COMPREPLY+=( "${candidates[@]}" )
done
return 0
}
if [[ "$SHELL" == *"zsh" ]]; then
autoload bashcompinit
bashcompinit
fi
complete -F _goto goto
complete -F _goto goto-which
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment