bash: tips and how-tos (1 of n)

Bash, which stands for Bourne-again shell, is a free Unix shell which is used also as a default command line for most Linux distribution. If you’re a Linux/Unix administrator or a Linux enthusiast, I’m pretty sure you’ve met the bash shell before.

These are some tricks in bash shell that I really find useful.

1. Don’t use backticks, use $( command ) instead.

I admit, this is one of the first tricks that I learned also. It’s quite adequate if you’re running just one command:

date_today=`date`

but if you’re planning to nest multiple commands:

current_pid=`cat $HOME/pid/my_pid.\`date +%y%m%d\`.pid`

Yes, you have to escape the backticks. Now, imagine if you have to nest 3 commands… What do you think it will look like?

We can write the two examples in $( command ) form,

date_today=$( date )
current_pid=$( cat $HOME/pid/my_pid.$( date +%y%m%d ).pid )

You can easily nest multiple commands and no “escapes” required. Your script will look tidier too.

2. Same command, different parameter… use {arg1,arg2,…,argN} trick:

If you find yourself running the same command with a different argument most of the time, you can find this trick useful.

user@localhost~$ wget http://file.example.com/file01.log
user@localhost~$ wget http://file.example.com/file06.log
user@localhost~$ wget http://file.example.com/file18.log

You can run this using {arg1,arg2,…,argN}:

user@localhost~$ wget http://file.example.com/file{01,06,18}.log

You can even combine multiple values:

user@localhost~$ wget http://file.example.{com,net,org}/file{01,06,18}.log

Please note that this doesn’t work with some commands, like echo, so test your script first.

3. Same set of commands, different parameter… create a function.

Yes, bash supports functions. If you’re running a set commands and you want to reuse it, this is the way to go.

To declare a function:

function my_function () {
first_parameter=$1
second_parameter=$2 # so on and so forth…

# things to do…
}

Here’s a simple script that I wrote to back up necessary configuration files in my work station.

#!/bin/bash

BACKUP_DIR=$HOME/config.backup

function backup() {
local file # don’t make this variable global

file=$1 # assign first parameter to file

if [ “x$file” != “x” ] # if $file is empty, don’t process
then
mkdir -p $BACKUP_DIR
# create the destination directory
cp $file $BACKUP_DIR
# copy the file
fi
}

backup /etc/apt/sources.list
backup /etc/samba/smb.conf
backup /etc/X11/xorg.conf

That’s it for now. I hope you find these tips useful. Thanks for dropping by.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s