Some handy bash commands
Saturday, February 14, 2009 at 5:24PM
Mattie

On Linux shells, I always feel pretty crummy about getting around quickly via cd. So, in the spirit of Daniel's up command, here's a few other quick-directory commands to add to your .bashrc:

# up somesubdir
# Find a directory below this that matches the word provided
# (locate-based)
function down() {
dir=""
if [ -z "$1" ]; then
dir=.
fi
dir=$(locate -n 1 -r $PWD.*/$1$)
cd "$dir";
}

# cdd someglobaldir
# quickly change to a directory anywhere that matches the word you typed.
# best if your locatedb is in good shape
function cdd() {
dir=""
if [ -z "$1" ]; then
dir=.
fi
dir=$(locate -n 1 -r $1$)
cd "$dir";
}

Other variations that I tried:


# Not breadth-first, so less fun sometimes
function down2()
{
dir=""
if [ -z "$1" ]; then
dir=.
fi
dir=$(find . -type d -iname $1 | head -n 1)
cd "$dir";

}

# Breadth-first, but really slow
function down3()
{
# create a list of all directories in the current folder
dirlist=( $(find . -maxdepth 1 -type d) )
dirlist=( ${dirlist[@]:1} ) # exclude .

# loop through the list
while [ $dirlist ]
do
# check the head of the list to see if it matches needle
val=${dirlist[0]}
found=`expr match "$val" ".*$1.*"`
if [ $found -gt 0 ]; then
# change dirs, we found the first match
cd "$val";
break # done
else
# not found!
# scan that new directory for subdirs
appendlist=( $(find $val -maxdepth 1 -type d) )
appendlist=( ${appendlist[@]:1} ) # exclude .
# add those subdirs to the tail of the dirlist
dirlist=( ${dirlist[@]:1} ${appendlist[@]} )

# rinse, repeat
fi
done

}

Posted via web from Imported from http://mattie.net/blog

Article originally appeared on Mattie.Net - Mattie Casper's Site (http://www.mattie.net/).
See website for complete article licensing information.