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:
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:
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:
This will offer a nice yellow prompt like in the screenshot below: