Shell Scripting by Examples
Different Quoting
#!/bin/bash
a=12
echo $a
echo "$a"
echo '$a'
IF Condition and Relational Operator
#!/bin/bash
num=12
if [[ $num -eq 12 ]] ; then
echo "NUmber found"
echo $num
else
echo "Number not found"
echo $num
fi
Handling Files
#!/bin/bash
if [[ -a /var/log/messages ]]
then
cat /var/log/messages | grep "Jul" > log.txt
fi
Use of Different Brackets
#!/bin/bash
# [[ Octal and hexadecimal evaluation ]]
decimal=15
hex=0x0f # = 15 (decimal)
if [ "$decimal" -eq "$hex" ]
then
echo "$decimal equals $hex"
else
echo "$decimal is not equal to $hex" # 15 is not equal to 0x0f
fi # Doesn't evaluate within [ single brackets ]!
if [[ "$decimal" -eq "$hex" ]]
then
echo "$decimal equals $hex" # 15 equals 0x0f
else
echo "$decimal is not equal to $hex"
fi # Evaluates within [[ double brackets ]]!
if (( decimal == hex))
then
echo "$decimal equals $hex" # 15 equals 0x0f
else
echo "$decimal is not equal to $hex"
fi # Evaluates within (( double brackets ))!
Easily evaluate arithmetic expressions
#!/bin/bash
a=12
b=1
echo $((a+b))
Using Shell command inside IF
#!/bin/bash
if [[ pwd == /home/jestinjoy ]];then
echo "We are in home directory"
pwd
else
echo "We are NOT in home directory"
pwd
fi
Command Line Parameters
cmd.sh
#!/bin/bash
i=$1
j=$2
((k=i+j))
echo Sum is $k
$./cmd.sh 1 2
3
Using Case statements
#!/bin/bash
echo "Enter your option: 1: add, 2:sub, 3: mul"
read i
case $i in
1) echo $(($1+$2));;
2) echo $(($1-$2));;
3) echo $(($1*$2))
esac
While Statement
#!/bin/bash
i=0
while ((i<10));do
echo $i
((i=i+1))
done
Using functions
#!/bin/bash
add()
{
i=$1
j=$2
((k=i+j))
echo Sum is $k
}
sub()
{
i=$1
j=$2
((k=i-j))
echo Sum is $k
}
mul()
{
i=$1
j=$2
((k=i*j))
echo Sum is $k
}
echo "Enter your option: 1: Add, 2:Subtract, 3: Multiply"
read i
case $i in
1) add 1 2;;
2) sub 1 2;;
3) mul 1 2
esac
For Loop and Selection Sort
#!/bin/bash
echo "Enter the total number of numbers"
read size
for ((i=0;i<size;i++));do
read p[i]
done
for ((i=0;i<size;i++));do
((min=i))
for (( j=i+1;j<size;j++ ));do
if (( p[j] < p[min] )) ;then
((min=j))
fi
done
((temp = p[i]))
((p[i]=p[min]))
((p[min]=temp))
done
echo "The Sorted Numbers are"
for ((i=0;i<size;i++));do
echo ${p[i]}
done