Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 12

Shell Programming

UNIX Architecture
It has 3 parts
1. Kernal 2.Shell 3. Utilities

1. Kernal
- core of OS
- Insulates other parts of OS from Hardware
- Performs Low Level Operations
- Parts of kernal deals with I/O devices,called device drivers
- All programs and applications interact with kernal

Kernal Functions:
- Memory management
- Process Scheduling
- File management and security
- Interrupt Handling and Error Reporting
- Input/Output services
- Date and time services
- System Accounting

2. Shell
- Interface between user and Kernal
- It is an command Interpreter
- It supports powerful programming facilities

Shell as a Programming Language - Features


1. Supports to execute a block of commands as a unit
2. Supports variables
3. Supports Conditional constructs
4. Supports Iteration control statements
5. Supports Positional Parameters.

Types of Shells:
1. Bourne Shell (bash)
2. C Shell (csh)
3. Korn Shell (ksh)

$ -- Bourne Shell
$ksh / csh
$ --- korn shell / c shell
$exit
$ -- Bourne Shell

3. Utilities
A collection of software tools supports different type of services.
Around 200 Utitlities are supported by Unix.

Shell Script
creating a Shell Script - Steps
1. open a new file using Vi editor
2. Type the list of commands
3. Save the file
4. Execute the file - $sh filename ( sh - command to execute the
Shell Script)

Ex: $vi script1


# Sample Shell Script
date
cal 2013 # comment line
who -H
# End of Script
:wq -- save n quit file

$ sh script1

Shell Variables
1. Environment Variables
- Defines the enviromment provided to user Login
2. User Defined Variables
- Created by users
3. Pre-defined Variables
- Created by Shell or commands. (i.e. ?)

Environment Variables:
PATH - Holds the path information provided to the user.

HOME - Holds the Home directory name

SHELL - Holds the Shell Name provided to the user

LOGNAME - Holds the User Login name

TERM - Holds the Terminal type information (vt100)

PS1 - Holds the primary Prompt($)

PS2 - Holds the Secondary Prompt (>)

PS1="SRI:" -- changing prompt

User defined Variables:


$variable=value ---> Defining a variable
$a=20
$b=30
$name="RAM"

Operators in Shell
Arthematic Numeric String
+ -eq =
- -lt !=
\* -gt -z - Returns
-le sucess if string is empty
/ -ge -n - Returns success if
-ne string is not empty

File Operators
-f - returns sucess if file exists
-s - returns sucess if file exists and not empty
-d - returns sucess if file exists & directory
-r - returns sucess if file exists & Readable
-w - returns sucess if file exists & Writable
-x - returns sucess if file exists and Executable

Logical:
-a -- and
-o -- or
! -- not

Commands:
expr - used to perform arthematic operations
bc - base calculator - used to perform arthematic opertions
echo - used to print messages or variable contents on to screen
test - used to check for conditions output will be stored in pre-defined variable
(?).

Using Commands:
$a=10
$b=20
$expr $a + $b { $variable - Gives the value of variable }
expr a + b --- ab
$c=`expr $a + $b` {variable=`command` }
( `` - Back Quotes )
$echo $c -- 30
$echo sum of numbers is `expr $a + $b`
sum of numbers is 30

$expr 234 + 3435


$expr 2300 - 210
$expr 23 \* 223
$expr 56 / 7
$day=`date +%A`
$echo $day --- sunday
-------------------------------------------------------
$bc --- base calculator [ + - * / % ]
23 + 3435
3458
12 * 5
60
8 * 4 + 8
40
^d (ctrl+d)
$

$name="SRIRAM"
$age=21
$echo "You are Mr.$name and you are $age years old"
You are Mr.SRIRAM and you are 21 years old

$vi script2
# Shell script printing Environment variables
echo "Path is $PATH"
echo "Shell is $SHELL"
echo "User name is $LOGNAME"
echo "Terminal type is $TERM"
# End of Script

$sh script2

read - used to read the variables


read <variable>

$vi kopy
# Shell script to copy files
echo "Enter source file :"
read source
echo "Enter Target file :"
read target
cp $source $target
echo "$source copied to $target file"
#end of script

$sh kopy
Enter source file :emp
Enter Target file :employ

Using Test command on different types data:


Output of test command is stored in pre-defined variable(i.e.?)
? -- 0 [ success ]
-- 1 [ failure ]

$a=10
$b=12
$test $a -eq $b
$echo $? -- 1
$test $a -gt $b
$echo $? -- 1
$test $a -lt $b
$echo $? -- 0

$name="SRIDHAR"
$course="UNIX"
$test $name != "Sridhar"
$echo $? -- 0
$test -n "$name" -n return success if string is
having content ( not empty - 0 )
$echo $? -- 0
$test -z "$drinks" -z return success if string is empty (0)
$echo $? -- 0
$test -n "$drinks" -- 1
$test -z "$name" -- 1
-------------------------------------------
$test -f file1
$test -d dir1
$test -s emp
$test -r emp -a -w emp $echo $?
$test ! -r emp -a ! -w emp
$test ! -d student
$test -r emp -o -w student
----------------------------------------------------
Conditional Operators :
1. && --- Command1 && Command2
If command1 is "success" it executes command2

$ ls|grep "temp" && rm temp

2. || --- Command1 || Command2


If command1 is "Failure" it executes command2

$cat emp || echo " File not found "


---------------------------------------------------------
Conditional Statements
1. if 2. case

Syntax : Simple if
if <condition>
then
<commands>
fi

Complex if
if <condition1>
then
<commands>
elif <condition2> elif // else if // elsif
then
<commands>
elif <condition3>
then
<commands>
else
<commands>
fi

# Shell script to Copy Files


echo "Enter source file:"
read source
echo "Enter Target file:" test --- [ ]
read target
if ( ls|grep "$target" ) // if test -s "$target" // if [ -s "$target" ]
then
echo " $target file exists - cannot copy files "
else
cp $source $target
echo $source copied to $target
fi
# end of script
Enter source file: file1
Enter Target file: file2

# shell script finds largest of 3 numbers


echo enter 3 numbers
read a b c
if test $a -gt $b -a $a -gt $c
then
echo $a is largest
elif test $b -gt $a -a $b -gt $c
then
echo $b is Largest
else
echo $c is Largest
fi
# end of script

Case Construct
used to check for multiple conditions easily.

Syntax:
case variable in
value1)commands;;
value2)commands;;
.
.
*)commands;;
esac

# Shell script using CASE construct


echo "1. Date & Time 2. Calender"
echo
echo "3. Users 4. Quit"
echo
echo "Choose ur option(1,2,3,4):"
read choice
case $choice in
1) date +"%D %T";;
2) cal;;
3) who -H;;
4) exit;;
*) echo "Wrong Choice ";;
esac

Iteration Control Statements:


Supports to execute a block of commands as a unit
repeatedly until conditions are True or False.

1. While Loop
Syntax:
while <condtion>
do
commands
done
* If condition is "True" it executes the block of commands

# Shell script Using While Loop


n=1
echo "The numbers are"
while test $n -le 10
do
echo $n
n=`expr $n + 1`
done
echo "end of numbers"

2. Until Loop
Syntax:
Until <condition>
do
commands
done
* If condition is "False" it executes the block of commands

#Shell script Using Until Loop


n=1
echo "The numbers are"
until test $n -gt 10 -- false (do)
do true ( end of numbers)
echo $n
n=`expr $n + 1`
done
echo "end of numbers"

3. For Loop
Entire loop choices must be given in for loop
Syntax:
for <variable> in <list of values>
do
commands
done

# Shell script using for loop


for i in 1 2 3 4 5 6 7 8 9 10
do
echo $i
done

# Shell script prints list of files (ls)


for i in *
do * -- represents all files in directory
echo $i
done

$vi escript
# Shell Script to create employ data file
ans="y"
while test $ans = "Y" -o $ans = "y"
# until test $ans = "N" -o $ans = "n"
do
echo "Enter employ code"
read ecode
if ecode -le 0
then
echo employ code is not valid
continue
fi
echo "Enter Employ name"
read name
echo "Enter basic pay"
read basic
if test $basic -le 0
then
break
fi
echo "$ecode:$name:$basic" >> emp.dat
echo "Do you want to continue( Y / N ):"
read ans
done
#End of Script

$sh escript

$cat emp.dat
101:ram:21000
102:anil:11000
103:raj:21000

continue -- restart the loop


break -- break the loop

Positional Parameters:
Supports to accept input from standard input device while execution itself.
Supports to make generalized scripts.
$# - Gives the no.of Parameters passed
$* - Gives the list of parameters
$1 to $9 - Holds the first nine parameters
shift - Removes the first parameter from list
set `command` - Stores the command output in parameters.

$ vi script1 [ open the file ]


# Shell script Using Parameters
echo "BEFORE SHIFT COMMAND"
echo " The no.of parameters are $# "
echo " The Parameters are $* "
echo " The First Parameter is $1"
echo " The Fifth Parameter is $5 "
shift
echo "AFTER SHIFT COMMAND"
echo " The no.of parameters are $# "
echo " The Parameters are $* "
echo " The First Parameter is $1"
echo " The Fifth Parameter is $5 "
# End of script
$sh script1 A B C D E F G H I J K L M N O

Output:
BEFORE SHIFT COMMAND
The no.of parameters are 15
The Parameters are A B C D E F G H I J K L M N O
The First Parameter is A
The Fifth Parameter is E
AFTER SHIFT COMMAND
The no.of parameters are 14
The Parameters are B C D E F G H I J K L M N O
The First Parameter is B
The Fifth Parameter is F

expr 25 + 50 + 40 + 60 -- invalid

expr 25 + 50
expr 40 + 60
expr 75 + 100

$vi addnum
# Shell Script to Add Given Numbers
tot=0
while test $# -gt 0
do
tot=`expr $tot + $1`
shift
done
echo "Sum of Given Numbers is $tot"
#End of script

$sh addnum 2 3 4 5
$sh addnum 12 34
$sh addnum 552 563 782 908 775
$sh addnum 33
$chmod 111 addnum
$mv addnum /bin --- Os admin

$addnum 222 333 444 555


$cp f1 f2
chmod -- used to change the file permissions

$vi kopy
# Shell script to copy files
# Check for given parameters
if test $# -lt 2
then
echo Minimum 2 File names has to be passed
else
if test !-s "$1" -o !-r "$1"
then
echo "Source file is Empty or Unable to read the file - Cannot copy files"
elif test -s "$2"
then
echo "Target file is already exists - Cannot copy files"
else
cp $1 $2
echo "$1 copied to $2"
fi
fi
#End of script

$sh kopy emp employ


[ emp,employ are file names ]

$chmod 711 kopy


$kopy f1 f2
$cp f1 f2
---------------------------------------------------------------------
Process Scheduling :

In an multi user environment any task performed by the


users enters in 3 stages.
1. Waiting
2. Execution
3. Sleeping

ps -- gives the process table contents

$ps
pid command time
1256 sh
3424 ps

$ps -ef -- gives all the process performed in server by all users

$ps -ef | grep "user1"

nice -- used to improve the priority of a command

$nice +10 vi
$nice +20 grep
$nice +15 sort

sleep -- used to make the process inactive for given time

$sleep 100
$sleep 50;date
du -- gives the disk usage details in user login

$du

df -- gives the disk free details in user login

$df

& -- background process


supports to execute multiple jobs by user at a time

$sh pay_gen -- process takes 1 hr

$sh pay_gen& -- registered in background and release the


$ prompt immediately to do next task.
$sh ann_rep&
$sh qtly_rep&
$ps -- gives the list of jobs running in server
$exit -- close all the tasks given by user

nohup -- no hang up
used to continue the background process after logout also.
output will be stored in nohup.out file.

$nohup sh ann_rep&
$nohup sh qtly_rep&
$nohup sh pay_gen&
$exit

It appends all the outputs to the nohup.out file


$cat nohup.out

kill -- used to terminate the process


kill pid
$kill 3035
$kill -9 4056 -9 - for confirmation

file -- gives the file type details

$file employ -- Ascii text


$file script1 -- shell script
$file a1.c -- C program
$file a101.sql -- sql file

find -- used to search for a file location & prints path

$find employ
$find a1.c

at -- used to execute the task at the specified time.


output of at command will be sent to mail.

$at 6pm
cp *.c cfiles
rm *.tmp
sh backup_script
sh close_script
^d
$

at dec 31
at now + 1 day
at 10:30 am
at 17:00
at mon next week

$ at -l -- list the jobs


$ at -e -- edit
-------------------------------------------------------------
Crontab: schedules the task on a particular
time(hr,min),date,month,day.

Crontab syntax :

* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6)
(Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31) date
| +----------- hour (0 - 23)
+------------- min (0 - 59)

Crontab Examples:

$crontab

30 18 * * * rm *.tmp
0 22 * * 1-5 cp *.c cfiles
* * 1,15,25 * * command
ctrl + d

cron -l
cron -e
-------------------------------------------------------------------------------
Using Admin commands :

login : root
password: xxxxxxxx
#pwd --- /

useradd -- used to create new users


userdel -- used to remove the existing users
passwd -- used to set the password for users

#useradd sridhar $passwd


#passwd sridhar
enter new password : xxxxxx
re-enter new password : xxxxxx

#userdel sridhar

wall -- used to send broadcast message to all currently working users in server.
sync -- used to update super block content manually
init 0 -- used to shutdown server
init 6 -- used to restart server

# wall
server is getting down in 5 min save ur works and logout
^d

#sync
#sync
#sync
#init 0
#init 6

Working with C program :


$ vi a1.c
main()
{
printf("First C program");
}

$ cc a1.c -- compiling C program


$ ./a.out -- executing C program

Working with C++ program :


$ vi b1.C
--------
--------

$ cc b1.C -- compiling C++ program


$ ./a.out -- executing C++ program

Working with Java program :


$ vi Demo.java
--------
--------
--------

$ javac Demo.java -- compiling java program


$ java Demo -- executing java class file

Working with Oracle Database :


login: user1
password: xxxxx
$
$ sqlplus
username : scott
password : tiger
sql> select * from emp;
.....
.....
sql> exit
$
-------------------------------------------------------------------------------
sri.oracle.ilogic@gmail.com
--------------------------------------------------------------------------------

You might also like