Bash Scripting

From ben.goodacre.name/tech

Jump to: navigation, search

BASH (Bourne Again Shell) is a command shell and interpretor for Linux.

Contents

Parameters

$# Number of parameters

$1 First parameter

$0 Name of the script

$@ All the parameters in one string

Variable Expansion

Get IP address

The following command will print the IP address by itself allowing you to pipe it into a command or an environment variable:

ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2|awk '{ print $1}'

Loops

Iterate through words in a string

users="tom jerry ben"
for character in $users
do
  echo $character is a good name
done

Looping through a series of numbers

for i in `seq 1 5`;
do
  echo $i
done

If

oldusers="tom jerry sam micky minnie"
if [ ! -d /var/spool/mail ]; then
        echo /var/spool/mail not found - check location
else
        echo Checking /var/spool/mail
        for user in $oldusers
        do
        if [ -e /var/spool/mail/$user ]; then
                echo /var/spool/mail/$user exists
        fi
fi

Numeric Operators

Single Braces

-eqequal
-nenot equal
-gtgreater than
-gegreater than or equal to
-ltless than
-leless than or equal to

Double Parentheses

Standard mathematical operators apply

<=less than or equal to
>greater than
>=greater than or equal to

String Operators

Single Braces

=equal
==equal, but has file globbing and word splitting when wildcarded without quotes, and literal matching with quotes
 !=not equal
-zstring is null
-nstring is not null - MUST be quoted string but string should always be quoted anyway...

Double Braces

<less than in ASCII order
>more than in ASCII order
==equal, but has pattern matching when wildcarded, literal matching with quotes

File Operators

Single Braces

-dDirectory
-e OR -aExists
-fRegular file
-h OR -LSymbolic link
-pNamed pipe
-rReadable by you
-sNot empty
-SSocket
-wWritable by you
-NHas been modified since last being read
-ntfile1 is newer than file 2. File modification time stamp is used.
-otfile1 is older than file 2. File modification time stamp is used.
- effile1 is a hard link to file2.

Test if number

[[ "$var" =~ ^[0-9]+([.][0-9]+)?$ ]] && echo $var is a number

Force run as root

if [ $UID != "0" ];then echo Only root can run this command 1>&2;exit 1;fi

Favorite Resources

BASH for beginners book
BASH Scripting Techniques
Steve Parker's Shell Scrpting Book
If
Operators and constructs

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox