« Please, Evernote, wake up. I wanted you to win. | Main | Using Second Life to create movies »
Saturday
Feb142009

Some handy bash commands

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

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (5)

Your advice is excellent!

September 23, 2010 | Unregistered Commenterserver hosting

Great information....
keep it up...

Weight loss pills | Quick weight loss | Caralluma Fimbriata

June 23, 2011 | Unregistered Commentercarababe

hey...this is great information...
thanks for sharing with us..
keep writing good..

Roofing Jacksonville | Roofer Jacksonville | Metal Roofing Jacksonville

June 28, 2011 | Unregistered CommenterRoofing Jacksonville

Hi,
I ran into this page mistakenly, surprisingly, this is a great website. The site owner has done a great job writing/collecting articles to post, the info here is really insightful. You just secured yourself a guaranteed reader.

June 8, 2012 | Unregistered Commenterroofing Jacksonville

Zsh has glob features that do something like what you've done.

February 26, 2013 | Unregistered Commenterzemnmeez

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>