Friday 17 February 2012

5 Cool and Useful Linux Command Line Tricks

Well using linux is fun and working on linux terminal is even more fun. Learning to use linux terminal and commands can prove very useful for personal as well as enterprise purpose. Today I'm going to talk about few cool and crazy linux commands that are less likely to be known by the average computer user.

1) The !$ trick: The !$ is a type of event designator that is present in bash as the feature. I'm not sure if other shells support it but bash does, for sure(I heard event designators are bash-specific). Anyway, !$ saves the last string from the previous command you've entered. The session in bash below shows what it actually does:

samar@Techgaun:~/Desktop$ mkdir test
samar@Techgaun:~/Desktop$ cd !$
cd test
samar@Techgaun:~/Desktop/test$

So when we give the mkdir test command, the !$ holds the value test So when we do cd !$, !$ is replaced by the string test which is the last string in last entered command.

2) The Don't Save This Command trick: Prepending your command with one or more space(<space>command) will not save the command in the bash history. This trick can be quite useful while doing password related stuffs and while sneaking in your friend's laptop.

3) The Oh! I forgot sudo trick: Well this is one of my favorite tricks and I named it so because I tend to forget to put sudo while running many commands and then I use this trick to prepend sudo at the beginning of the command. Below is the session when I used this trick recently.

samar@Techgaun:~$ cat /etc/sudoers
cat: /etc/sudoers: Permission denied
samar@Techgaun:~$ sudo !!
sudo cat /etc/sudoers
[sudo] password for samar:

*** Content Snipped to preserve length ***

As shown above, the !! is just another event designator. The !! actually holds the last used command and this can be alternatively specified as !-1. The !-1 version can be actually generalized to traverse back to history i.e. you can get any command in your history by using !-n convention.

4) The Clean up Terminal trick: Sometimes you open the binary and gibberish data and your terminal looks so ugly and needs some cleanup. In such cases, the command reset can be used which actually does is initialize the terminal.

5) Run previous command by replacing one string with another: Using the syntax ^abc^xyz^, you can run the previous command by replacing the string abc by the string xyz. The example below shows how I used the cat command after using the ls command. Its just an example, you could really make use of this trick for longer commands.

samar@Techgaun:~/Desktop$ ls /etc/hosts
/etc/hosts
samar@Techgaun:~/Desktop$ ^ls^cat^
cat /etc/hosts