Wednesday, December 22, 2010

10 Bash Tips for Working Faster With the Shell (Part 1 of 2)

SkyHi @ Wednesday, December 22, 2010
This command is used to bring back and automatically execute the last command in history. It is the same as pressing C^P followed by Enter). Here’s an example:


Using !text
Replacing ‘text’ with any command will call the last command in the history which starts with ‘text’. Example:
As you can see after issuing the first ls command we printed the working directory, then we called back the last ls command with !ls.

Using !n
This will bring up the nth command in history. This will vary depending on your history. Here’s an example:

Using !?text?
This will execute the most recent command that contains the word ‘text’. Example:
The most recent command containing the text ‘xjf’ was executed. This trick should be applied carefully though, especially for sensitive commands like rm.

Using !! in combination with another command
!! can also be used in combination with some other command, because the shell expands it first and then it executes the current command. For example, this can be very useful in combination with sudo, since sometimes we forget to use administrative privileges for commands that need it. For example:

Changing the color of the Bash prompt
There are many ways of customizing your Bash prompt, and I will list here only a few pre-defined sets.
To make the user’s prompt green, put this inside your ~/.bashrc file, where ~ is your home directory:

Now run source ~/.bashrc or . ~/.bashrc to read the settings again. Here’s how your prompt should look like:


Here’s another example, which will make your prompt look really fancy:

And this is how it will look like:

A pretty good tutorial on this can be found here (Bash Prompts How-To) and several prompt schemes on the Arch Wiki, here. The Bash Reference manual section on this include some useful information too.

Catch the exit status of a command with $?
If a command is successful, its exit status will be 0, otherwise it will be different from 0. This can be useful in scripts.

Using reversed search: Ctrl-R
Ctrl-R will prompt you to enter a pattern for a command, and will search the history in reversed order for any the first command that contains the pattern and execute it. Example
In the above example we issued the ls -lh command, the pressed Ctrl-R and typed in the letter L. The command was brought up and then executed with Enter.

Using cd – to go to the previous working directory
This command will have the same effect as cd $OLDPWD, where $OLDPWD is a variable that holds the previous working directory.

Using grep -e -pattern to show the lines that start with a – sign
This will be useful if piped to commands like man, for example:
This will query the manual page for gcc and will only print lines that contain the text -ansi.


REFERENCES
http://www.tuxarena.com/?p=257