Last active
December 16, 2015 01:39
-
-
Save rcmdnk/5356658 to your computer and use it in GitHub Desktop.
moved to https://github.com/rcmdnk/sd_cl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Directory store file | |
export LASTDIRFILE=$HOME/.lastDir | |
# Number of store directories | |
export NLASTDIR=20 | |
function sd { # Save dir {{{ | |
# Set values | |
local ldf=${LASTDIRFILE:-$HOME/.lastDir} | |
local nld="${NLASTDIR:-20}" | |
# Get last directories | |
touch $ldf | |
local dirs=() | |
while read d;do | |
dirs=("${dirs[@]}" "$d") | |
done < $ldf | |
local ld=${dirs[0]} | |
# Push current directory | |
local curdir=`pwd -P` | |
if [ "$ld" != "$curdir" ];then | |
dirs=("$curdir" "${dirs[@]}") | |
fi | |
# Store directories | |
local i=0 | |
rm -f $ldf | |
while [ $i -lt ${#dirs[@]} ] && [ $i -lt $NLASTDIR ];do | |
echo "${dirs[$i]}" >> $ldf | |
i=$((i+1)) | |
done | |
} # }}} | |
function cl { # Change directory to the Last directory {{{ | |
local HELP=" | |
Usage: cl [-lch] [-n <number> ] | |
If there are no arguments, you will move to the last saved dirctory by sd command | |
Arguments: | |
-l Show saved directories | |
-c Show saved directories and choose a directory | |
-n Move to <number>-th last directory | |
-h Print this HELP and exit | |
" | |
# Set values | |
local ldf=${LASTDIRFILE:-$HOME/.lastDir} | |
# Initialize variables | |
local nth=0 | |
local list=0 | |
local choice=0 | |
# OPTIND must be reset in function | |
local optind_tmp=$OPTIND | |
OPTIND=1 | |
# Get option | |
while getopts cln:h OPT;do | |
case $OPT in | |
"c" ) choice=1 ;; | |
"l" ) list=1 ;; | |
"n" ) nth="$OPTARG" ;; | |
"h" ) echo "$HELP" 1>&2;OPTIND=$optind_tmp;return ;; | |
* ) echo "$HELP" 1>&2;OPTIND=$optind_tmp;return ;; | |
esac | |
done | |
shift $(($OPTIND - 1)) | |
OPTIND=$optind_tmp | |
# Get last directories | |
touch $ldf | |
local dirs=() | |
while read d;do | |
dirs=("${dirs[@]}" "$d") | |
done < $ldf | |
local ld=${dirs[0]} | |
# List up and choose directory | |
if [ $choice -eq 1 ] || [ $list -eq 1 ];then | |
# List up stored directories | |
local listnum=${#dirs[@]} | |
local i=$((listnum-1)) | |
while [ $i -ge 0 ];do | |
printf "%4d %s %4d\n" $i "${dirs[$i]}" $i | |
i=$((i-1)) | |
done | |
# Choose from STDIN | |
if [ $choice -eq 1 ];then | |
echo -n "choose directory number: " | |
read nth | |
fi | |
fi | |
# Change directory | |
if [ $list != 1 ];then | |
cd "${dirs[$nth]}" | |
fi | |
} # }}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment