More Bash tips

Following on from a post I made a while ago below are some more Bash tips. Hopefully you find a few of them useful...

Note: Like the last post, some of the shortcuts below assume you are using the default emacs style line editing mode. You can check this by running set -o | grep emacs. For more info have a look at the Bash command line editing docs.

Controlling the prompt

By default your bash prompt will probably look something like this:

[user@example ~]$

The prompt is controlled by the PS1 environment variable. In the example above PS1 is set to [\u@\h \W]$. The escaped characters are replaced with the following:

  • \u: username of the current user
  • \h: the hostname of the system
  • \W: the basename of the current working directory

The Bash documentation gives a full list of special characters that can be used. In addition you can also execute code in a prompt. For example the line below will add a smiley or sad face to the prompt based on the return code of the previous command:

PS1='[ \u@\h $([ $? -eq 0 ] && echo -e "\e[32m:)" || echo -e "\e[31m:(")\e[m ] $ '

After setting PS1 the prompt should look something like this:

[ user@example :) ] $ true
[ user@example :) ] $ false
[ user@example :( ] $

Note: To make changes persistent set PS1 in ~/.bash_profile.

Useful cd options

Below are a couple of useful ways to call cd:

  • Running with no arguments (cd) will take you to your home directory.
  • Running with a dash (cd -) will take you to the previous working directory.

Yank last arg

It's fairly common to run multiple commands with the same last argument. For example:

 $ vim /some/very/log/file/path/example.py
 $ chmod 755 /some/very/log/file/path/example.py
 $ chgrp foo /some/very/log/file/path/example.py

Instead of repeating the file path multiple times you can use the following shortcut:

alt + .

Doing this will insert the last argument from the previous command. So in the example above after running vim you would type chmod 755 followed by they keyboard shortcut to insert the file path.

Clear screen

It's often nice to clear any previous commands off the screen. Instead of using the clear command, the following shortcut can be used:

ctrl + c

Undo edits

It's very easy to accidentally delete the wrong part of a command you're editing. For example if you press ctrl + w in the wrong place. You can actually undo edits using the following shortcut:

ctrl + _

Brace expansion

Bash has a useful feature called brace expansion. It works by expanding an expression inside curly brace characters ({ and }) to generate multiple arguments. For example, if you want to make a backup of a file you can run:

cp -p /etc/foobar.conf{,.backup}

Bash will then expand the expression to the following:

cp -p /etc/foobar.conf /etc/foobar.conf.backup

You can also use brace expansion with a sequence. For example:

$ touch example_{1..4}.txt
$ ls
example_1.txt  example_2.txt  example_3.txt  example_4.txt