Skip to content

Instantly share code, notes, and snippets.

@bobbydavid
Created September 19, 2012 23:07
Show Gist options
  • Save bobbydavid/3752931 to your computer and use it in GitHub Desktop.
Save bobbydavid/3752931 to your computer and use it in GitHub Desktop.
bash: give yourself useful recent directories with `cd` and `d` commands
#!/bin/bash
#
# Change directories, but with pushd functionality.
#
# 1) change to given directory.
# 2) add that directory to the stack.
# 3) delete any duplicates of it on the stack.
# 4) delete stack above $MAX_DIR_STACK_SIZE
#
# Find full path for destination directory.
if [ $# -eq 0 ]; then
DIR="$HOME"
elif [ $# -gt 1 ]; then
echo "cd $@: TOO MANY ARGUMENTS ARGGHHH" >&2
return 1
elif [ "$1" = ".." ]; then
DIR=`realpath ..`
elif [ "$1" = "-" ]; then
DIR=`realpath ~-`
else
DIR=`realpath "$1"`
fi
# Push directory.
pushd $DIR >/dev/null || return $?
# Remove duplicates.
EXISTING=`dirs -l -v | grep " ${PWD}\$" | egrep -o "^\s*[1-9][0-9]*" | sort -nr`
for NUM in $EXISTING; do
NUM=`echo "$NUM" | tr -d ' '`
popd -n +$NUM >/dev/null || return $?
done
# Truncate stack, if necessary.
if [ "$MAX_DIR_STACK_SIZE" ]; then
COUNT=`dirs -l -v -0 | awk '{print $1}'`
while [ "$COUNT" -gt "$MAX_DIR_STACK_SIZE" ]; do
popd -n -0 >/dev/null || return $?
COUNT=$(( $COUNT - 1 ))
done
fi
#!/bin/bash
dirs -v | awk -F" " '
BEGIN {
OFS=" "
}
{
w='`tput cols`'
xtra=length($0) - w
if (xtra > 0) {
plen = length($2)
split($2,pieces,"/")
pcount = length(pieces)
postfix="/ ... /" pieces[pcount]
remaining = length($2) - xtra - length(postfix)
str = ""
for (i = 2; i < pcount; i++) {
remaining = remaining - length(pieces[i]) - 1
if (remaining > 0) {
str = str "/" pieces[i]
}
}
$2=str postfix
}
print $0
}'
Recommend to add aliases in `~/.bashrc` to use this scripts. For example:
alias cd='. ~/bin/cd-pushd.sh'
alias d='. ~/bin/dirs-good'
Causes, for example:
$ d 0 ~/bin
1 ~
2 /srv/www/project/ ... /long-directory-name
3 /srv/www/project/ ... /long-directory-name-2
4 /srv/www/project/ ... /long-directory-name-3
which you can then switch to using tilde, e.g.
$ cd ~4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment