Sunday, February 19, 2012

[TIP] Use Linux Pipelines and Make your life easier

Suppose you want to get the history of your terminal (commands, that you have typed  in the terminal) and find out a command that you have used log time ago.

So you can simply use history command to list down command history and find it.

$ history

( By default Linux store only last 1000 history of your command line. you can find the history file and size of history by typing following command. you can change these values changing global profile value of the terminal. )

$ echo $HISTFILE 
$ echo $HISTSIZE

But if your list is bigger one you may need to do a search to find your command. 
for example you can use grep command to find it. See following command set.

$ history > history.txt 
$ grep -i "dpkg" history.txt
 1761  dpkg -s jflex
 1974  dpkg -s cup
$ rm history.txt

In first command it writes history into a text file. In the second line, it search for "dpkg" with ignoring the case in the history.txt and it shows the results in next two lines. After that in the 5th line it removes the history.txt file.

But we can do this easily using Linux pipelines. It generates no intermediate files and can obtain result using one line. here is the command.

$ history | grep -i "dpkg" 
 1761  dpkg -s jflex
 1974  dpkg -s cup 

This is a simple example that use Linux pipelines. You can use this for very complex stuffs.  Read this Wikipedia page to learn more on Linux pipelines.

Here is another example that use pipeline.

$ find . -name .svn | xargs rm -fr

this command removes all .svn directories in current path.( Also you can use non pipeline solution to do this. see following command )

find . -name .svn -exec rm -rf {} \;

No comments:

Post a Comment