BASH tips

Here’s a few BASH-tips I find very useful in the shell:

Swapping

One feature I hate that my TV does not have, is to fast and easy be able to switch between two channels. Turns out that BASH does a better job than my TV. Before I knew about this little trick I used pushd and popd. Painfull in comparison to this:

# Start off in $HOME
$ pwd
/home/rejeep

# Go to Apache virtual host configuration files
$ cd /etc/apache2/vhosts.d/
$ pwd
/etc/apache2/vhosts.d

# Go back to $HOME
$ cd -
$ pwd
/home/rejeep

# Go back to Apache conf.
cd -
$ pwd
/etc/apache2/vhosts.d

Fast path completion

How often do you move a file or folder to a different folder and then want to visit the target folder? I guess this is how you do it?

mv my_cool_site.conf /etc/apache2/vhost.d
cd /etc/apache2/vhost.d

The question is: How did you get the path as argument to cd? Used the mouse? Typed it again? Well… Try typing cd, and the press M-. (Alt and dot). Voila!

mv my_cool_site.conf /etc/apache2/vhost.d
cd M-.

ls after cd

I always, no matter what, want to list the current folders contents when I enter it. So after a while when gotten tired of typing ls all the time. I wrote a little function to do the job:

# Does ls after cd.
function cd()
{
  builtin cd ${1:-$HOME} && ls
}

Put this in your ~/.bashrc file and then source it with source ~/.bashrc and try it out.

Fast ls

As you might figure out from the previous tip, I like to know what I have in the current folder, all the time. The above only helps if I move around between different folders. So I needed something when changing a lot in the current folder.

bind -x '"\C-o"':"ls -lh"

Put this in your ~/.bashrc file and then source it with source ~/.bashrc and try it out by pressing C-o (Ctrl and o).

Recursive word count

What do you do if you want to know how many lines of code all java files are togheter? You use wc, right? But what if you want to count all files recursively? Then wc cannot do the job on it’s own. And that’s the beauty of piping. Since the command to do the job is quite long and I do it quite often, I created a little script for it:

#!/bin/bash

# Given a folder or a file and a file extension, this will print out
# the total number of lines recursive with that extension.
#
# Usage:
#   rrc java ~/dev/java/project
#   rrc html.erb ~/dev/rails/project
#   rrc rb

if [[ $# -lt 1 ]]; then
    echo "USAGE: rcc extension [path/file]"

    exit 1
fi

# Source code path.
path=$(cd ${2:-.} && pwd)

echo -n "LOC in ${path}: "
find $path -iname *.$1 -type f -exec cat {} \; | wc -l

blog comments powered by Disqus Back to Top

Fork me on GitHub