我有一个习惯就是把代码工程都放在一个目录里,命名为 Code。每天打开 Terminal,我都是先切换到 Code 目录,然后在看看需要到那个工程目录开发。后来,我在 github 上看别人的 dotfiles,发现了这个函数,分享给大家,希望大家喜欢。
https://github.com/xiaods/dotfiles/blob/master/bash_config.sh
用起来特简单,打开 Terminal,输入 work 就到你的工程目录,想到 fork 下来的 ruby-china,就输入 work ruby-china。
# shortcut to workspace
export SHARED_WORKSPACE="$HOME/Documents/Code"
# `work foo` to navigate to SHARED_WORKSPACE/foo.
work() {
dir=$(workspace)
cd "$dir/${1}"
}
# Used by work() and _work() to determine workspace your projects live in. Set
# the SHARED_WORKSPACE environment variable if this is not ~/workspace/.
workspace() {
result=$([ -s "$SHARED_WORKSPACE" ] && echo $SHARED_WORKSPACE || echo "~/workspace/")
echo "$result"
}
# bash completion function for work(). Allows you to type `work f` to
# auto-complete to `work foo`, following standard Bash directory-completion
# rules.
_work() {
local cur
local trim
local dir=$(workspace)
cur=${COMP_WORDS[COMP_CWORD]}
# length of expanded path, used to trim off first portion of matched paths below
trim=`echo $dir/ | wc -c`
# perform completion, returning all directories in workspace, trimming off the path to the workspace
COMPREPLY=( $( compgen -S/ -d $dir/$cur | cut -b $trim- ) )
}
# enable completion for work() function using _work(), but only if `complete` exists
command -v complete > /dev/null && complete -o nospace -F _work work