BashScript

Basics

Shell Declaration

#!/bin/bash

Variables

count=5
greeting=Hello\ World
hello="Hello World $count"
demo='Hello World $count'
echo "$count"
echo "$greeting"
echo "$hello"
echo "$demo"

5
Hello World
Hello World 5
Hello World $count

Arrays

area1[51]=sometext
area2=( zero one two three four )
area3=([17]=seventeen [24]=twenty-four)
echo ${area1[51]}
echo ${area2[0]}
echo ${area3[17]}
echo ${#area2[*]} # Number of elements in array.
echo ${#area3[@]} # Number of elements in array.
echo ${#area2[1]} # Length of second element
echo ${area2[@]}

sometext
zero
seventeen
5
2
3
zero one two three four

Commandline Interaction

echo "Enter your name : "
read name
echo "Hello $name. Have a nice day."

Positional Parameters
$#Stores the number of commandline arguments
$?Stores the exit value of the last command that was executed
$0Stores the first word of the entered command (the name of the shell program)
$*Stores all the arguments that were entered on the command line ($1 $2 ...)
"$@" Stores all arguments individually quoted ("$1" "$2" ...)

Operators

integer operators
1 -eq 2True if 1 is equal to 2
1 -ge 2True if 1 is greater than or equal to 2
1 -gt 2True if 1 is greater than 2
1 -le 2True if 1 is less than or equal to 2
1 -lt 2True if 1 is less than 2
1 -ne 2True if 1 is not equal to 2
string operators
str1 = str2True if str1 is identical to str2
str1 != str2True if str1 is not identical to str2
strTrue if str is not null
-n strTrue if the length of str is greater than zero
-z strTrue if the length of str is zero
file operators
-d filenameTrue if filename is a directory
-f filenameTrue if filename is a file
-r filenameTrue if filename can be read
-s filenameTrue if filename has a nonzero length
-w filenameTrue if filename can be written
-x filenameTrue if filename is executable.
logical operators
! exprTrue if expr is not true
expr1 -a expr2True if expr1 and expr2 are true
expr1 -o expr2True if expr1 or expr2 is true

Conditional Statements

if [ expression ]
then
   commands
elif [ expression2 ]
then
   commands
else
   commands
fi

case string1 in
str1)
   commands;;
str2)
   commands;;
*)
   commands;;
esac

Iteration Statements

for var1
do
   statements
done

str="this is a string"
for arg in $str
do
   echo "$arg"
done

while expression
do
   statements
done

until expression
do
   commands
done

Examples

# As we are piping into a while loop, variables from the subshell
# are not available in parent scoope. This example shows howto
# get content from a subshell into a variable available in parent
# scope.

x=$(
ps h -C getty -o command | while read line
do
   expr "$line" : "/sbin/getty \(.*\)"
done
)
echo $x

Functions

fname () {
   shell commands
}

fname parm1 parm2 parm3 ...

Links

Bash Guide for Beginners
Ubuntu Beginners BashScripting