Thursday, December 11, 2008

BASH Basics

Following are some basics on how BASH gets initialized and core programming constructs.

BASH initialization

When you first login, bash reads these initialization files in order (if they exist):

/etc/profile -- systemwide profile applies to all users

Then, it looks for these files and executes the FIRST one it finds (note that the file names start with a period):
$HOME/.bash_profile
$HOME/.bash_login
$HOME/.profile

For interactive non-login shells, it executes:
$HOME/.bashrc

At logout, it executes:
$HOME/.bash_logout

Built-in shell variables:

These can be referenced interactively, but usually they are used in a shell script. A shell script is a plain text file that contains BASH commands executed in the order they appear. It is a program executed by BASH.

$# number of command line arguments
$? exit value of last command
$$ process ID of current process
$! process ID of last background process
$0 command name of the current process
$n (n=1-9) the 1st thru 9th command line arguments
$* all command line arguments
$@ all command line arguments, individually quoted ($1 $2 ...)

If statement

if condition ; then
commands
elif condition ; then
commands
else
commands
fi

Test the return status of the previous command:

if [ $? == 0 ] ; then
commands
fi

Loops

while condition; do
commands
done

for var in list; do
commands
done

for (( expr1; expr2; expr3 )); do
commands
done

Case statements

The case statement can be used in place of a complex if statement.

case expression in
pattern)
commands
;;
pattern)
commands
;;
*
commands
esac