作ったきっかけ
gitのルートディレクトリに移動したい❗
深い階層に潜っていると戻るのが面倒臭い😩
自分で書けばいいや😄
ラッパー関数
以下のようなディレクトリ構造で例えます。
git-root
┣━ foo
┃ ┗━ bar
┗━ baz
- カレントディレクトリが
git-root
以下のときにcd /
でgit-root
に移動 - カレントディレクトリが
git-root
の場合はcd /
で/
に移動 - カレントディレクトリが
baz
のときにcd /foo/bar
でgit-root/foo/bar
に移動-
git-root
以下に対象のディレクトリが無ければ、/
以下を探す
-
ラッパー関数を作る
gitcd() {
# 引数が / で始まらない
# または ホームディレクトリの path で始まる場合、普通に cd
if [[ ! "${1}" =~ "^/.*" || "${1}" =~ "^${HOME}.*" ]]; then
builtin cd "${@}"
return
fi
# プロジェクトディレクトリの中じゃなければ普通にcd
local insideProject=`git rev-parse --is-inside-work-tree 2>/dev/null`
if [ ! "${insideProject}" = "true" ]; then
builtin cd "${@}"
return
fi
local currentDir=`pwd 2>/dev/null`
local projectRoot=`git rev-parse --show-toplevel 2>/dev/null`
# git-root に居れば / に移動
if [ "${currentDir}" = "${projectRoot}" -a "${1}" = "/" ]; then
builtin cd "/"
return
fi
# /path/to が git-root 以下にあれば git-root/path/to に移動、
# 無ければ /path/to に移動
if [ -d "${projectRoot}${1}" ]; then
builtin cd "${projectRoot}${1}"
else
builtin cd "${@}"
fi
return
}
alias cd=gitcd
これで完成です✨
今後の課題
git-root
以下で cd /
とタイプしたときに git-root
以下のディレクトリを補完したい😣
ということでそのうち補完も効くようにしたいです、、、が補完周りはよくわからないのでしばらく先になりそうです😵
最後に
私のdotfilesです。よかったら参考にしてください。
シェルスクリプトは痒いところに手が届いて気持ちいいですね🙌