If you have multiple software repositories, how do you move between them?
Possibly you have all repositories checked out into the same parent directory?
Do you cd .. a lot?
1 2 3 4 5 6 7 |
user@machine:~/code$ cd repo1 user@machine:~/code/repo1$ cd .. user@machine:~/code$ cd repo2 user@machine:~/code/repo2$ cd .. user@machine:~/code$ cd repo3 user@machine:~/code/repo3$ cd .. ... |
Save some time by making a new “go-to-repository-command”. Let’s call this command “r”. Mine looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
REPOSITORY_DIRECTORY="/Users/olof/code" function r { cd "${REPOSITORY_DIRECTORY}/${1}" } if [[ -n "${ZSH_VERSION}" ]]; then autoload -U +X compinit && compinit function _r { _files -W "${REPOSITORY_DIRECTORY}" } compdef _r r elif [[ -n "${BASH_VERSION}" ]]; then function _r { COMPREPLY=( $( compgen -d "${REPOSITORY_DIRECTORY}/${2}" ) ) COMPREPLY=( ${COMPREPLY[@]#${REPOSITORY_DIRECTORY}/} ) if [[ "${#COMPREPLY[@]}" -eq 1 ]]; then COMPREPLY[0]="${COMPREPLY[0]}/" fi } complete -F _r -o nospace r fi |
The function itself is pretty short. Adding tab completion is the tricky part. The solution above supports both bash and ZSH. The following links was useful when coding it:
- https://stackoverflow.com/questions/9910966/how-to-get-shell-to-self-detect-using-zsh-or-bash
- https://stackoverflow.com/questions/38737675/different-directory-for-bash-completion
- https://stackoverflow.com/questions/34406433/zsh-completions-based-on-a-directory
- https://stackoverflow.com/questions/3249432/can-a-bash-tab-completion-script-be-used-in-zsh
Simply typing “r” will take you to the parent directory.
Typing “r repo1” will take you directly to the repo1 child directory, regardless of where you are currently standing.
Tab completion always acts as if you were standing in the parent directory.
Now you may skip cd .. entirely!
1 2 3 4 5 |
user@machine:/tmp/somedir$ r repo1 user@machine:~/code/repo1$ r repo2 user@machine:~/code/repo2$ r repo3 user@machine:~/code/repo3$ git status ... |
You may want to investigate which terminal commands you commonly use. Perhaps cd .. is there?
[…] Here’s a suggestion for what to make of “r” but you may also want to shorten the commands you type the most often. […]