Bash is one of those Unix things that I am fully aware has a lot more potential and power than I know how to use. Every so often I go looking for another handful of useful things to learn about it: this is a selection of recent ones.

Firstly: the Debian bash package includes a file /etc/bash_completion which extends bash - for example, enabling zsh-style tab completion of hostnames. Source this file in your own .bashrc to get this functionality. It also makes it easy to extend/program bash yourself, via the directory /etc/bash_completion.d/, which is automatically sourced by /etc/bash_completion. For example, suppose you have a script foo.sh which takes hostnames as arguments (e.g. one which applies a particular command across a set of hostnames). You can get hostname tab-completion on foo.sh by creating a file /etc/bash_completion.d/foo which contains the line

complete -F _known_hosts foo.sh
You can also, of course, can get a lot more complicated - this article talks about getting tab-completion for any other arguments to foo.sh.

Secondly: $CDPATH is to cd what $PATH is to executables. Set $CDPATH in your .bashrc as follows:

export CDPATH=.:~:/usr/local/:/opt/my/long/dir/path
Then if you wish to change to /opt/my/long/dir/path/subdir, just type cd subdir at the prompt and you’re there. Note that you do need to include . in there or you won’t be able to change directories within your current directory.

Thirdly, some small useful .bashrc things:

  • shopt -s cdspell will attempt to correct misspellings of directories.
  • shopt -s dotglob allows files beginning with a dot to be returned in filename expansions.
  • export HISTCONTROL=ignoreboth stops the bash history from including either duplicate lines, or lines beginning with a space, which makes it rather quicker to navigate.
and some small useful command-line shortcuts:
  • Ctrl-r searches backwards in your bash history. I love this one very much.
  • Alt-. (that’s a full stop there) inserts at the cursor the last argument to the previous command.
  • Alt-Ctrl-y inserts at the cursor the first argument to the previous command. Further: if you hit Alt-3 then Alt-Ctrl-y, you’ll get the 3rd argument to the previous command.

Finally: a little snippet for your .bashrc that will change the title of your xterm or xterm-alike to show username@hostname:/current/directory. It updates as you change directory or ssh to another host. This is useful if you spend a lot of time opening lots of xterms on various hosts and in various directories; and it’s another visual clue as to (e.g.) whether you’re currently logged in as root. Myself, I also set my root prompts to be in a different colour to my own prompts. You can’t have too many reminders of your identity…

case $TERM in
    xterm*)
        PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}:${PWD}\007"'
        ;;
    *)
        ;;
esac

Comments with other useful bash bits and pieces welcome!