Bash Tips & tricks

Here are some tips & and tricks about bash that I consider useful and use regularly. This is not a bash tutorial, some bash knowledge is assumed.

Some words about the notation used:

Moving aroung directories

Environment variables

Useful keybindings (in Emacs mode)

Here is a list of the keybindings I use most in bash.

C-aGo to the beginning of the line
C-eGo to the end of the line
C-lClear screen
C-uCuts the text from the beginning of the line to the caracter before the cursor
C-kCuts the text from the caracter under the cursor to the end of the line
C-yPaste text
M-?List all possible completions
M-*Insert all possible completions after the cursor
M-.Last command's last argument
M-number letterRepeats letter number times


bash has support for recording and executing macros. You can start recording a macro with the keybinding C-x ( and stop it with C-x ). You can then execute the recorded macro with C-x e

Readline related

Executing commands

Shell scripting

Tab-completion on steroids

Try to install the package bash-completion. In debian it is installed by default. If it is installed on your system you should have the file /etc/bash_completion

The bash-completion package provides tab-completion behaviour for more things that only filenames: environment variables, ssh hosts, options for common commands.... To use it all you need to do is to source /etc/bash_completion.

The following example shows some (there is a lot more!) of the magic of bash-completion ([TAB] is used to represent a tab keypress):

$ . /etc/bash_completion
$ ssh a[TAB]

$ ssh l[TAB][TAB] localhost
$ ssh l

$ tar [TAB]
A c d r t u x
$ tar

$ ls --c[TAB]
--classify --color --color=
$ ls --c

$ echo $P
$ echo $P

This tip was contributed by Ramón Pons

A better ~/.profile

I don't like having all my configuration (aliases, environment variables, etc...) on just one file. It looks quite messy to me, and making changes becomes increasingly difficult as the file grows. So instead of having one big ~/.profile I have several small, specialized files in a directory called ~/.profile.conf. The files are the following:

Of course, an special ~/.profile script is needed to read all these files. Here is my ~/.profile:


# Aliases
if [ -f "$PRFDIR/aliases" ] ; then
	while read ALIAS CMD; do
		if [ "$ALIAS" != "" ] && [ "$CMD" != "" ] ; then
			alias $ALIAS=$CMD
	done < $PRFDIR/aliases
	unset IFS

# Environment variables
[ -f $PRFDIR/env ] && . $PRFDIR/env

# PATH variable
if [ -f $PRFDIR/path ] ; then
	while read LINE; do
	done < $PRFDIR/path

# Execute and source start scripts
if [ -f $PRFDIR/autosource ] ; then
	. $PRFDIR/autosource

if [ -f $PRFDIR/autoexec ] && [ -x $PRFDIR/autoexec ] ; then