Edited at

ブラウザの戻る進むみたいにディレクトリを移動するやつ

More than 5 years have passed since last update.


元ネタ

http://tabesugi.net/video/yusuke-bashrc.html

これを見ていたらブラウザの戻る進むみたいに移動するスクリプト(bash)が紹介されていたので

zshで書いてみた


ソース


.zshrc

path_history=($(pwd))

path_history_index=1
path_history_size=1

function push_path_history {
local curr_path
curr_path=$1

if [ $curr_path = $path_history[$path_history_index] ]; then
# do nothing
else
local path_history_cap
path_history_cap=$#path_history

if [ $path_history_index -eq $path_history_cap ]; then
local next_cap
next_cap=$(($path_history_cap * 2))

# ほんとに伸長されているかは不明
path_history[$next_cap]=
fi

path_history_index=$(($path_history_index+1))
path_history[$path_history_index]=$curr_path
path_history_size=$path_history_index
fi
}

function - {
if [ $path_history_index -eq 1 ]; then
# do nothing
else
path_history_index=$(($path_history_index-1))

local prev_path
prev_path=$path_history[$path_history_index]

cd $prev_path
fi
}

function + {
if [ $path_history_index -eq $path_history_size ]; then
# do nothing
else
path_history_index=$(($path_history_index+1))

local next_path
next_path=$path_history[$path_history_index]

cd $next_path
fi
}

function reset_path_history {
path_history=($(pwd))
path_history_index=1
path_history_size=1
}

function chpwd {
push_path_history $(pwd)
}



使いかた


ひとつ前に戻る

$ cd /

$ cd tmp
$ -
$ pwd
/


ひとつ後に進む

...上の続き

$ +
$ pwd
/tmp


履歴消去

$ reset_path_history


おまけ

現在の履歴を確認する関数とpeco使って移動する関数も書いてみた


~.zshrc

function hist {

local pad
pad=$#path_history_size

for i in {$path_history_size..1};do
if
[ $i -eq $path_history_index ]; then
printf "%${pad}d -> %s\n" $i $path_history[$i]
else
printf "%${pad}d %s\n" $i $path_history[$i]
fi
done

}

function hp {
local index
index=$(hist | peco | head -n 1 | tr -d '\n' | sed -e 's/^\s*\([0-9]\+\).*$/\1/')

expr "$index" + 1 >/dev/null 2>&1
if [ $? -ge 2 ]; then
# do nothing
elif [ $index -lt 1 -o $index -gt $path_history_size ]; then
# do nothing
else
path_history_index=$index

local next_path
next_path=$path_history[$path_history_index]

cd $next_path
fi
}



hist


hp

pecoとgnu版のsedが必要です

(Macとかだとデフォで入っているsedがbsd版なのでこっちを入れておく)