Saturday, 11 July 2015

Shell Scripting


A shell script is a computer program designed to be run by the Unix shell, a command line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text.In the simplest terms, a shell script is a file containing a series of commands. The shell reads this file and carries out the commands as though they have been entered directly on the command line.

The file name should have the extension .sh
like filename.sh

To Execute the file we have to give execution permission.like
     chmod +x filename.sh
to execute
     ./filename.sh
Or we can execute the file without changing the permissions, like
. filename.sh
Let's see some examples on the shellscripting

1.#To print the user name
open a file with the name 1.sh as
vi 1.sh
copy the below line to that file
echo “Hello $USER”
save and quit the file with
Esc :wq
execute the file with the command
. 1.sh
output:
Hello episteme

2.#to take the input from the user and print the output
echo "enter a value"
read a
#read -t 2 a :to wait for 2 sec
echo "enter b value"
read b
echo "a value: $a"
echo "b value: $b"
output:
enter a value
1
enter b value
2
a value:1
b value:2

3.programming with command line arguments
#to print command line arguments
echo $*
#to print number of command line arguments
echo $#
#to print command line arguments
echo $@
Output:
./3.sh 1 2 3
1 2 3
3
1 2 3

4.#To find to numbers are equal or not using conditional statements
a=$1
b=$2
echo "a value: $a"
echo "b value: $b"
if [ $a -eq $b ]
then
          echo "$a and $b are equal.."
else
           echo "$a and $b are not equal.."
fi
Note: Here $1 and $2 are argv[1] and argv[2] respectively(command line arguments).
Output:
./4.sh 1 2
a value: 1
b value: 2
1 and 2 are not equal..

5.#to check whether a file is existed or not
if [ -e $1 ]
then
             echo "file $1 is existed"
else
             echo "file $1 is not existed"
fi
output:
./5.sh 1.sh
file 1.sh existed
./5.sh hi
file hi is not existed

6.#shell script to implement arithmetic operations using switch statement
echo "enter a value"
read a
echo "enter b value"
read b
echo -e "1:add\n2:sub\n3:mul\n"
read c
case $c in
1)echo "result: $(($a + $b))";;
2)echo "result: $(($a - $b))";;
3)echo "result: $(($a * $b))";;
esac
Output:
enter a value
1
enter b value
2
1:add
2:sub
3:mul
1
result: 3

7.#To perform arithmetic operations
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val" 

val=`expr $a - $b`
echo "a - b : $val" 

val=`expr $a \* $b`
echo "a * b : $val" 

val=`expr $b / $a`
echo "b / a : $val" 

val=`expr $b % $a`
echo "b % a : $val" 

if [ $a == $b ]
then
echo "a is equal to b"
fi 

if [ $a != $b ]
then
echo "a is not equal to b"
fi
Output:
a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a is not equal to b


No comments:

Post a Comment