Skip to content

Instantly share code, notes, and snippets.

@tueda
Last active October 19, 2015 12:54
Show Gist options
  • Save tueda/9253579 to your computer and use it in GitHub Desktop.
Save tueda/9253579 to your computer and use it in GitHub Desktop.
copyd & pasted: change the working directory to one in the saved list. #bin
#!/bin/bash
# Usage: load this file as
# . copyd.sh
# which defines the following commands:
#
# copyd
# Copy the current directory on the top of the directory list.
# pasted
# Change the current directory to the first directory in the list.
# pasted <number>
# Change the current directory to the <number>-th directory in the list.
# pasted <keyword>
# Change the current directory to one in the list that contains the keyword.
# histd | copyd - | pasted -
# List the directory list.
COPYD_HISTFILE=$HOME/.copyd_history
COPYD_MAXLINES=10
COPYD_ABSPATH=1
COPYD_COLORHIST=1
COPYD_CL_NORMAL='[0m'
COPYD_CL_MISSING='[37m'
copyd() {
if [ "$1" == "-" ]; then
_copyd_list
return
fi
if [ 0"$COPYD_ABSPATH" -ne 0 ]; then
local dir=`pwd -P`
else
local dir=`pwd`
fi
_copyd_add "$dir" && echo "$dir"
}
pasted() {
if [ "$1" == "-" ]; then
_copyd_list
return
fi
if [ $# -gt 0 ]; then
_copyd_move $1
else
_copyd_move 1
fi
}
histd() {
_copyd_list
}
_copyd_cat() {
local src=$COPYD_HISTFILE
[ -f "$src" ] || src=/dev/null
cat "$src"
}
_copyd_add() {
[ -z "$1" ] && return 0
local tmp=$COPYD_HISTFILE.$$.$RANDOM.$RANDOM
local lines=`_copyd_cat`
{
echo "$1"
echo "$lines"
} | awk '!x[$0]++' \
| head -n $COPYD_MAXLINES >"$tmp" && \
mv -f "$tmp" "$COPYD_HISTFILE"
local ret=$?
rm -f "$tmp"
return $ret
}
_copyd_list() {
{
if [ 0"$COPYD_COLORHIST" -ne 0 ]; then
local line
_copyd_cat | while read line; do
if [ -d "$line" ]; then
echo "$line"
else
printf "\e$COPYD_CL_MISSING$line\e$COPYD_CL_NORMAL"
echo
fi
done
else
_copyd_cat
fi
} | sed = | sed 'N;s/\n/ /'
}
_copyd_move() {
local lines=`_copyd_cat`
if [[ "$1" =~ ^[[:digit:]]+$ ]]; then
local dir=`echo "$lines" | sed -n $1p`
else
local n=`echo "$lines" | \grep -c "$1"`
if [ $n -ge 2 ]; then
echo "pasted: more than one candidates for '$1'" >&2
echo "$lines" | sed = | sed 'N;s/\n/ /' | \grep "$1" >&2
return 1
fi
local dir=`echo "$lines" | \grep "$1"`
fi
if [ -z "$dir" ]; then
echo "pasted: '$1' not found" >&2
return 1
fi
cd "$dir" && { echo "$dir"; _copyd_add "$dir"; }
}
# vim: ft=sh et ts=8 sts=2 sw=2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment