Wednesday, October 21, 2009

Shortcut: Pipe Your Output and Change Directory

Objective: Piping your output into the "cd" command can have many uses. I want a Google "I'm Feeling Lucky" option when locating files on my filesystem, thus saving me the time and energy of typing out a long path once I've found it's location.

Script:
# cd $( dirname $( locate type.in.search.value.here | head -n 1 ))

How it works: 
Let's work from the inside out. 
The "head" command by default prints the first 10 lines of a file. # head messages
With the -n switch we can decide exactly how many lines we want to print to the standard output or in this case, a variable.
The "locate" command is my current favorite search tool in Linux, just don't forget to use # updatedb to update your directory database so that this command works properly. 
Typically, if I run # locate daniel  I'd see /home/daniel plus every file in that directory on my terminal. When we pipe the output of #locate daniel to # head -n 1 then the output is only the first result. 
The markings $(   ) take what ever is inside the parenthesis and create somewhat of a temporary variable. This allows for a different kind of pipe. At the root try this # echo home | cd . Now, try this, 
# cd $( echo home ) . Similar way of piping commands, but sometimes it's better to use one than the other. 
The "dirname" command outputs whatever is behind the leading / of a path. # dirname /home/daniel would out put /home and # dirname /home/daniel/temp.txt would output /home/daniel. Because you can't change directory to a file name, this allows us to go to the containing folder for the file we are searching for. So we pipe the results of the dirname to cd, which takes us to our destination. 
That's a lot of typing, and in most cases it would be quicker to just type the path while hitting tab a couple times to complete long folder names. We can this as a function to your BASH profile, that is if BASH is your shell. BASH is all I know, but I'd love to post instructions for other shells if you got them. 
Open up /home/$user/.bashrc
# vi /home/daniel/.bashrc
Adding a function is easy by typing
function name.of.function
{
} 
Insert your code between the brackets, with one difference
function gimmie
{ # cd $( dirname $( locate $1 | head -n 1 )) } 
In BASH, the variable $1 is the value of first command line parameter, with $2 being the second and so on. This variable accepts whatever command parameter we pass to it.
# gimmie temp.txt
temp.txt will get passed to $1, locate will find its location, head will take the first result being /home/daniel/temp.txt, dirname will strip away the filename temp.txt and cd will change our present working directory to /home/daniel
Credits: Thanks for helping me come up with this script. 
LinuxQuestions.org members:
GrapefruiTgirl, PTrenholme, :::, catkin, Tinkster, pixellany      


No comments:

Post a Comment