Wednesday 12 August 2009

5 Simple Bash Tips, Part III

This is the third article in the Bash tips series, you can find the other two here and here.

1. Use cd - to go to the previous working directory

cd - is the same as cd $OLDPWD, where the $OLDPWD variable holds the previous working directory. You can also alias this to something like:

alias back='cd -' # or alias back='cd $OLDPWD'

If you've just opened a new Bash session or sourced .bashrc, the $OLDPWD variable will be unset. Also, follow this discussion on reddit which is a great resource on this matter.

2. Make copies of files easier
This one is especially useful for creating backup files, but not only. To fasten up rename commands like mv file1 file1bak you can use something like:

mv file1{,bak}

Here, Bash will expand this command into mv file1 file1bak and execute it afterwards.

3. Search history backward or forward
This one is very popular due to its usefulness. Add the following two lines inside your .bashrc file:

bind '"\e[A"':history-search-backward
bind '"\e[B"':history-search-forward

Now type a command, for example ls, and then press the Up or Down arrows. You will see how it autocompletes the last ls commands. This will not change the default behaviour of Ctrl+P and Ctrl+N.

4. Use grep -e "-pattern" to search man pages for entries starting with -
This one is not necessarily a Bash tip, but you can use it to search man pages for entries that start with characters like -

man gcc | grep -e "-Wall"

5. Change the Bash prompt colour
You can customise your Bash prompt the way you like, including colours and what to display. Here's a simple example, just add this line at the end of .bashrc:

PS1="\[\033[1;33m\]$USER@$HOSTNAME$ \[\033[0m\]"

This will offer a nice yellow prompt like in the screenshot below:


1 comment:

anytux said...

Here's another option for prompt:

For user prompt, in file /home/user/.bashrc:

#PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' PS1='\[$(tput setaf 2)\]\u@\h:\w\n$ \[$(tput sgr0)\]'

For root prompt, in file /root/.bashrc:

#PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' PS1='\[$(tput setaf 1)\]\u@\h:\w\n$ \[$(tput sgr0)\]'

Other prompt colors:

tput setaf:
1 = red (dark)
2 = green
3 = orange (dark)
4 = blue (dark)
5 = magenta (dark)
6 = blue (turqois)
7 = gray
8 = red (bright)
9 = white

NOTE:
1. The user prompt will be green.
2. The root prompt will be red. This is not bad when you're using a distro with root.
3. The dollar sign will be displayed on the new line so you can enter a long command and still see the current directory path.
4. If you're using Nautilus as file manager and you have the 'nautilus-open-terminal' plugin installed, when you right-click (in any directory) and select "Open in Terminal" you will get the current directory path in the prompt.