There are many shells (interpreters) available on UNIX
•
•
•
•
2
There are 3 widely used shells namely: Bourne shell C Shell Korn Shell or K-Shell
LY2000 0 SL C/UNI X/JU LY200
Bourne Shell •
Known after the inventor Steve Bourne
•
Very popular
•
3
Comes with UNIX
LY2000 0 SL C/UNI X/JU LY200
C Shell •
Created by Bill Joy
•
Used by serious UNIX programmers
•
•
•
4
It allows aliasing of commands Command history maintenance. This is more like the DOS doskey. These are the two key features
SL C/UNI X/JU LY200 LY2000 0
Korn Shell •
Also known as K-shell
•
Designed by David Korn of AT&T
•
•
5
Very powerful Superset of Bourne shell
LY2000 0 SL C/UNI X/JU LY200
Access to UNIX •
Access to UNIX is given through login & password
abc login: abc password : xyz •
•
•
6
login & password will be created by the system administrator password is not visible while typing After 3 successive failures of login, the login will be disabled LY2000 0 SL C/UNI X/JU LY200
Access to UNIX •
•
•
•
7
If the login or password is not entered correctly, it will give „login „login incorrect‟ incorrect‟ message It won‟t tell which is not correct - login / password. This is a security measure After the successful login, it will go to „$‟ prompt for ordinary user, „#‟ prompt for super user The prompt can be changed through PS1 SL C/UNI X/JU LY200 LY2000 0
UNIX Commands •
All UNIX commands should be entered in lower case
•
Between thethere command andatthe arguments, must be least one space or tab e.g.: ls -l All command flags will be given with (Hyphen) •
8
LY2000 0 SL C/UNI X/JU LY200
UNIX Commands •
One or more flags flag s can be clubbed
e.g.: ls -l -a can be given as ls -la •
•
DEL-key erases characters and cancels a command Terminal should not be turned-off as soon as the work is over. Press ^d ^d (Ctrl+d) to come into login: login: prompt prompt
9
LY2000 0 SL C/UNI X/JU LY200
UNIX file system Creation of login involves •
•
•
10
Identifying login name to the user Identifying initial password Identify a group for the user
•
Identifying a default shell to the user
•
Identifying a working directory
LY2000 0 SL C/UNI X/JU LY200
UNIX file system •
UNIX understands everything as a file. It may be disk, terminal, directory or file.
•
•
•
11
A file is a stream of bytes. A file will have properties like block special, character special devices etc. A file system begins with a directory called root root
LY2000 0 SL C/UNI X/JU LY200
UNIX file system - root directory •
Denoted by „/ „/‟ slash slash
•
Every directory will branch from root
•
•
•
12
Other directories under root directory are bin, lib, usr, etc, tmp & dev Contains the kernel (UNIX) All directories will have files with specific purpose
Contains the binary files i.e. executables exec utables
•
UNIX commands are mostly C programs
•
14
or shell programs Shell programs are collection of several UNIX commands
LY2000 0 SL C/UNI X/JU LY200
UNIX file system - lib directory •
Contains library functions
•
The programmers under UNIX will use these libraries
15
LY2000 0 SL C/UNI X/JU LY200
UNIX file system - dev directory •
•
•
•
16
Contains device driver files of input / output The devices like terminals, printers, disk drivers etc Separate file for each device Each device is implemented as a file
LY2000 0 SL C/UNI X/JU LY200
UNIX file system - usr directory •
Contains several user directories
•
Created by system administrator when
•
•
•
creating new accounts Each user is allowed to work in his directory often known as home directory User can organize his directory by creating subdirectories usr contains another bin directory containing additional UNIX commands
17
LY2000 0 SL C/UNI X/JU LY200
UNIX file system - tmp •
•
Contains temporary files created by UNIX or by other users Will be deleted by UNIX at shutdown time
18
SL C/UNI X/JU LY200 LY2000 0
Date - Command This command is used to display the current System date or set the system date. Example : $ date Thu Nov Nov 8 03:13:18 MST 2007 $ date +%a Thu $ date +%A Thursday $ date +%b Nov $ date +%B November $ date +%d 08 $ date +%D 11/08/07 $ date +"%r %a %d %b %y" 03:18:59 AM Thu 08 Nov 07
19
SL C/UNI X/JU LY200 LY2000 0
Creating files •
Can be created using two commands touch & cat
$touch touch file1 file2 … Creates file-name-1, file-name-2 file-name-2 … files of zero size •
•
Used to create several empty files
20
SL C/UNI X/JU LY200 LY2000 0
Creating files - cat $cat > > file1 •
•
•
Whatever typed will go to the file file1 Press ^d (Ctrl+d) to abort the cat command ^d inserts the EOF (End Of File)
character $cat file1 file1 •
Displays the contents of the file1
21
SL C/UNI X/JU LY200 LY2000 0
Creating files - cat •
Can be used to concatenate files by:
$cat file1 file2 file2 > file3 •
•
•
Creates file3 containing file1 followed by file2 Overwrites if file3 is already existing No warning will be given if it is overwriting
22
SL C/UNI X/JU LY200 LY2000 0
Creating files - cat •
To add to file3 by:
$cat file1 file2 file2 >> file3 •
Appends the contents of file1, file2 to file3
23
SL C/UNI X/JU LY200 LY2000 0
CAT Command •
Can create files
•
Can club files
•
•
Can be used to see the files Can append to files
24
SL C/UNI X/JU LY200 LY2000 0
File Copy Command - cp •
To copy file1 to file2 by:
$cp file1 file2 •
To copy files to directory $cp file1 file2 dir-name Can copy files across directories by providing absolute or relative path: $cp cp /usr1/file1 /usr2/file1 •
25
SL C/UNI X/JU LY200 LY2000 0
File Delete Command - rm •
Removes the file
•
The file removed can not be recovered
•
like in DOS using undelete Care should be taken while deleting:
$rm file1 •
Removes file1
26
SL C/UNI X/JU LY200 LY2000 0
File Delete Command - rm $rm -i file1 •
Removes file interactively. Removes after
confirmation $rm -r dir1 •
Removes files from dir1 recursively
$rm -ir dir1 Removes file from dir1 recursively and interactively •
27
SL C/UNI X/JU LY200 LY2000 0
File Rename Command - mv •
To rename file1 as file2 by:
mv $ file1 file2 •
To rename directories by: mv $ old-dir new-dir •
mv actually copies old-file to new-file and removes old-file
28
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
Provides the current directory listing:
$ls •
Provides the directory contents: $ls dir-name •
•
Displays the file names in alphabetically sorted order Won‟t display the file names starting with „.‟ period. period.
29
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
To display all files including the files starting with „.‟ „.‟
$ls -a To display only file-names starting with a,b,c only •
$ls [a-c]* To display long listing •
$ls -l
30
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
$ls -l gives something like this
total 32 -rwxr-x--x
1 usr1 group1 24 jan 00 10:13 file1
drwxr-x--x -rwxr-x--x
1 usr1 group1 24 jan 00 10:13 file2 2 usr1 group1 24 jan 00 10:13 file3 file3
•
•
total 32 means current directory occupied 32 blocks Generally each block in UNIX is 1024
31
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
•
•
•
•
•
•
The next 9 characters provides the information about file permissions permissio ns Next column gives the number of links Owner name Group name File size in bytes Date & Time of last modified Finally the file-name
32
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
Owner concept comes with multi-user OS
•
The file creator is the owner by default
•
Group is formed with same type of users
•
Anybody other than the above are others
•
•
•
The first 3 characters in permission field is owner permissions The next 3 characters tells about the group permissions Last 3 characters gives the other permissions
33
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
There are three types of permissions like
•
r - read permission
•
•
w - write permission x - execution permission
rwxr-x--x means •
Owner of this file has read, write and execute permissions
•
Group has read and execute permissions perm issions
•
Others has only execution permissions
34
SL C/UNI X/JU LY200 LY2000 0
File Listing Command - ls •
Permissions can be encoded numerically
•
Read ( r ) - Weight 4
•
•
•
•
Write ( w ) - Weight 2 Execute ( x ) - Weight 1 The weight of Read+Wright+Execution (rwx) is 4 + 2 + 1 = 7 The weight of Read+Execution (r-x) is 4 +1=5
35
SL C/UNI X/JU LY200 LY2000 0
File Change Permission - chmod •
•
Existing file permissions can be changed with the command chmod To change the rwxr-x--x (751) permissions to rwxrwxrwx (777) permissions of file1 is
$chmod 777 file1 To give write permission to all •
$chmod +w file1
36
SL C/UNI X/JU LY200 LY2000 0
File Change Permission - chmod •
To remove write permissions to all including the owner
$chmod -w file1 The above command is generally used to keep a file safe by making it READ•
ONLY
37
SL C/UNI X/JU LY200 LY2000 0
Directory Permissions •
A directory is also a file for UNIX
•
Directory will have the permissions as
•
•
that of any file A directory is writable if the user has write permissions etc 754 are the most widely used permissions for a directory
38
SL C/UNI X/JU LY200 LY2000 0
Directory Commands - pwd •
•
User goes to home directory upon successful login To know which directory we are currently in:
pwd $ •
pwd stands for present working directory
39
SL C/UNI X/JU LY200 LY2000 0
Directory Commands - mkdir •
To create a new directory below current directory:
$ new-dir-name mkdir To create multiple versions of directory: mkdir -p dir1/dir2/dir3 $ •
•
Creates dir1 first. Creates dir2 under dir1. Creates dir3 under dir2.
40
SL C/UNI X/JU LY200 LY2000 0
Directory Commands - mkdir •
To create a directory with given permissions:
$ 754 new-dir mkdir -m new-dir will be created with 754 permissions •
41
SL C/UNI X/JU LY200 LY2000 0
Directory Commands - rmdir •
To remove a directory:
$rmdir dir-name •
•
rmdir can remove only empty directories To remove directory along parent directory:
$rmdir -p dir1/dir2/dir3 •
Deletes all the directories
42
SL C/UNI X/JU LY200 LY2000 0
Directory Commands - cd •
Stands for change directory
•
Used to navigate among directories
$cd dir1 dir1 Takes to dir1 directory •
$cd •
•
Takes to the home directory Can give full-path-name or relative-pathname as argument
43
SL C/UNI X/JU LY200 LY2000 0
UNIX commands - banner •
Prints the given string in big letters
banner <string> $banner <string>
44
SL C/UNI X/JU LY200 LY2000 0
UNIX commands - touch •
Used to change the last access time of a file
$touch -a -a file1 acces ss t i m e Changes the acce of file1 with of current time •
$touch touch file1 Changes access time as well as modification time will be changed to •
current time
45
SL C/UNI X/JU LY200 LY2000 0
UNIX commands - file •
Used to know the file type like shell script, executable
$file file file-name file-name english text
46
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - wc •
Used to know the number of characters, number of files and number of lines in a
file wc $wc file1
wc $wc -l -l file1 •
•
Displays the number of lines in file1 Can take the input from terminal directly
47
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - sort •
Used to sort a file
$sort sort file1 •
•
Sorts file1 and displays the sorted file on terminal Instead of displaying the sorted file on
terminal, can be written in to a file by: $sort –o file2 file1 •
Writes the sorted file1 in file2
48
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - cut •
Cut is a filter.
•
Picks up given number of bytes from a
given file by: $cut -f -f 5,10 file1 •
Displays 5th field to 10th field in file1. Each field is assumed to be separated by TAB character
49
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - grep •
•
•
This is the good example exam ple of unfriendly UNIX command Acronym for „G „Globally search a R egular egular Expression and Print it‟ it‟ Searches for a pattern in file(s)
$grep grep abc file1 Searches for the string „abc‟ in file1 file1 •
50
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - head •
Displays only first few lines of a file as per the argument
$head -15 -15 file1 Displays only first 15 lines of file1 •
51
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - tail •
Displays only last few lines of a file as per the argument
$tail -15 -15 file1 Displays the last 15 lines of file1 •
52
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - pg/more •
Both commands work almost like the same with few differences
pg $pg +5 -20 -p -s -s file1 Starts displaying file1 20 lines per page, starting from 5th line, with prompt for •
each page of display
53
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - lp •
Sends the user print job to the print queue
$lp lp file1 file2 request id is lp-23(2 files) •
•
•
Many flags available for different ways of printing Can take the input from terminal
54
SL C/UNI X/JU LY200 LY2000 0
UNIX file commands - lpstat •
Gives the printer status like which is currently printing, how many jobs are
still in queue etc $lpstat -t -t scheduler is running system default destination : lp device for lp: /dev/lp0 lp accepting requests since <date> < date> •
A „>> „>>‟‟ indicates the appending of data to a file if it exists, instead instea d of over-writing tandarr d Output 1>&2 indicates - redirect Standa 1>&2 indicates tanda ndarr d Er r or to Sta < Command-1> | <Command-2> means Command-1>
the standard output of Command-1 Co mmand-1 is going to be the standard input of Command-2
61
SL C/UNI X/JU LY200 LY2000 0
I/O Redirection & Piping •
UNIX supports joining of commands through „|‟ piping character character
$ls ls | wc -l The output of ls is the input for wc •
outfile outfile $ls | wc -l > •
Output of wc will be written in outfile
62
SL C/UNI X/JU LY200 LY2000 0
I/O Redirection & Piping •
•
Output of first process will be written to pipe and the pipe then hands it over to the next process. tee can be used to capture the pipe file
who $ | tee file1 | sort •
Output of who will be written into file1 and the file will be sorted and the sorted file will be written writte n to standard output
63
SL C/UNI X/JU LY200 LY2000 0
UNIX Command - ps •
To see the processes running currently under UNIX can be had by:
$ ps ps PID
TTY
2266
tty2 0:06
sh
2269
tty2 0.02
ps
•
TIME
COMMAND
Process Status command is shortly known as ps
64
SL C/UNI X/JU LY200 LY2000 0
UNIX Background Process •
•
•
•
Time consuming tasks may be run in background Place „& „&‟ at the end of the command, comma nd, the process will go to background Displays the PID after submission Success or failure of the background process will not be reported
65
SL C/UNI X/JU LY200 LY2000 0
UNIX Background Process •
Better to redirect the background process output to some file. Otherwise, it will disturb the foreground process messages on the screen
•
•
Too many background processes will degrade the performance If logged out, all the background processes will be terminated
66
SL C/UNI X/JU LY200 LY2000 0
UNIX Command - Sleep This command is used us ed to delay a process for a period of time For Example : To run a command at regular intervals, enter: while true do date sleep 60 done This shell procedure displays the date and time once a minute. To stop it, press the Interrupt key sequence.
67
SL C/UNI X/JU LY200 LY2000 0
Killing a Process •
To terminate a process
$kill kill PID PID •
An user can kill only his processes
68
SL C/UNI X/JU LY200 LY2000 0
UNIX Communication - write •
•
Any user can „write‟ a message on other user‟s terminal. terminal. Other user should give permissions to write message
Hello will Hello will be written on user-name‟s user-name‟s
terminal 69
SL C/UNI X/JU LY200 LY2000 0
UNIX Communication - write •
•
•
The <User-name> user should be loggedin to receive the message The recipient should give permissions for message Message writing can be denied by:
mesg $mesg -n Super user can write to any terminal without permissions •
70
SL C/UNI X/JU LY200 LY2000 0
UNIX Communication - finger •
Can find who are the users who set message -n by:
$finger -i -i Login TTY When abc
*tty1 …
def ghi
tty2 … tty3 …
•
Idle
a „*‟ before the tty means - set „mesg -n‟ n‟
71
SL C/UNI X/JU LY200 LY2000 0
UNIX Communication - motd •
•
The „Message of the day‟ news will be typed in a file called „/etc/motd „/etc/motd‟. ‟. The contents will be displayed upon login. News like „The system will be taken for maintenance from 14.00 Hrs to 16.00 Hrs‟ so that the users will schedule their work accordingly.
72
SL C/UNI X/JU LY200 LY2000 0
Shell Programming •
A shell program is a series of UNIX commands
•
Instead of typing the commands one after the other, the commands may be written in a file and execute the file.
•
Shell programming offers much more versatility than mere UNIX commands
•
Almost a system can be developed by
using shell script with UNIX commands 73
SL C/UNI X/JU LY200 LY2000 0
Shell Programming •
•
UNIX shell is the interface between the operating system & user
•
It is an interpreter, not an executable A shell script can be executed by giving execute permissions ($chmod ($chmod +x shell) shell) or
•
by shell command ($sh shell) Shell programming is so powerful, even system shutdown like tasks can be
handled 74
SL C/UNI X/JU LY200 LY2000 0
Shell Programming •
•
Three shells available under UNIX Bourne, C & Korn shell The following shell scripts were written in Bourne shell
•
Bourne shell script will work with Korn
•
shell and the reverse is not true Bourne is the default shell in most of the installations
75
SL C/UNI X/JU LY200 LY2000 0
Shell Programming •
•
•
•
•
Shell scripts are used to accomplish variety of tasks like: Customizing the working environment Automating the daily tasks like backups etc Automating repetitive tasks Executing important system procedures like shutdown
76
SL C/UNI X/JU LY200 LY2000 0
Shell Programming •
When the user logins into the system, the UNIX starts a shell (sh) on that terminal which accepts commands from „$ „$‟ prompt
•
When a shell-script is given for execution, the shell executes the commands from the shell-script
77
SL C/UNI X/JU LY200 LY2000 0
Interactive Shell Programming •
Two basic words in shell are read & echo &
•
read accepts input
echo writes the output echo Enter your name \? •
read name echo Good morning $name •
Write the above 3 lines in a file name
sh01 78
SL C/UNI X/JU LY200 LY2000 0
Interactive Shell Programming $sh01 Enter your name ? Vijay Vijay Good morning Vijay •
The „\ „\‟ symbols makes the shell to understand „?‟ as an ordinary character rather than special character
•
Double quotes (“) may be used to display a string
79
SL C/UNI X/JU LY200 LY2000 0
Interactive Shell Programming •
•
name is a shell variable receives data from keyboard $name will display the contents of the variable
80
SL C/UNI X/JU LY200 LY2000 0
Interactive Shell Programming echo Enter three values X Y Z read x y z echo $x $y $z $z •
If 1 2 3 entered, x will have 1, 2 to y & 3 to z
•
If 1 2 3 4 are entered, then z will have 3 4
•
•
If only 1, 2 are entered, then z will be assigned null value If more arguments entered, last variable will be assigned rest. If less, null will be assigned
81
SL C/UNI X/JU LY200 LY2000 0
Interactive Shell Programming •
echo This is new line \nAnd this is second line
•
The above will be displayed as This is new line
And this is second second line •
The escape sequence was brought from C language
82
SL C/UNI X/JU LY200 LY2000 0
Interactive Shell Programming •
\b is blank, \t is tab char etc.
•
To make the cursor at the end of the
echoed line echo “Enter your Name
:\c”
Enter your Name :_ (Cursor waits here) •
echo “\007 “\007” ” gives bell bell
83
SL C/UNI X/JU LY200 LY2000 0
Shell Variables •
•
•
•
They are an integral part of shell programming Provide ability to store and manipulate data Fully under the control of the shell Can create and destroy the variables as the user wants
84
SL C/UNI X/JU LY200 LY2000 0
Shell Variables - Guidelines •
•
•
•
•
Any combination of alphabet, numbers and underscore( _ underscore( _ ) No editing characters like commas, blanks The first character of the name should be alpha or underscore May be of any reasonable length Case sensitive ie abc & Abc are different
85
SL C/UNI X/JU LY200 LY2000 0
Shell - Assigning values •
Values can be assigned to variable using „=„ equal sign sign
From this time onwards, UNIX displays ABC as prompt
88
SL C/UNI X/JU LY200 LY2000 0
System Variables •
•
PS2 is prompt string 2, default value is „>‟ PATH defines the directories to searched by shell to execute any command or file
•
HOME defines the default working
•
directory LOGNAME stores the log name of the user
89
SL C/UNI X/JU LY200 LY2000 0
System Variable •
•
•
MAIL stores the file name of the mailbox along path MAILCHECK duration of the mail checking SHELL keeps the default shell name
90
SL C/UNI X/JU LY200 LY2000 0
System Variables •
•
TERM gives the name of the terminal the user is using All the above variable values can be known by set command
$set •
Displays all the values
91
SL C/UNI X/JU LY200 LY2000 0
Tips & Traps •
All the variables are string variables
•
$a=20. 20 is stored as a string not as number.
•
No arithmetic can be carried on this Use double quotes if the value contains more than one word
$name=“Vijay Suri” •
Can assign more than one variable in a line
$name=“Vijay” age=20
92
SL C/UNI X/JU LY200 LY2000 0
Tips & Traps •
Can display more than one variable in a line
$echo Name is $name $name and and age is $age •
All variables in a shell script are automatic variable. i.e. they will be created as soon as the shell script execution starts and dies as soon as the execution is over
93
SL C/UNI X/JU LY200 LY2000 0
Tips & Traps •
A null variable can be created crea ted by
$a1=“” or a1=„‟ or a1= •
Shell ignore if any shell variable is having null value
94
SL C/UNI X/JU LY200 LY2000 0
Unchanging Variable - readonly •
User can make a variable unchanged during execution by:
$age age= =20 $readonly readonly age •
The the shell does not allow us to change the value
95
SL C/UNI X/JU LY200 LY2000 0
Wiping out Variable - unset •
A variable can be removed from the shell by using unset command
$unset unset age Unset can not be used for system variables •
•
$unset PS1 is not allowed
96
SL C/UNI X/JU LY200 LY2000 0
Positional Parameters •
Many occasions, a program expects the variables in a certain fashion. This is achieved through positional parameters from $0 through $9.
•
$0 is $0 is the program itself. Thus
$abc par1 par2 par3 par4 assigns abc to $0, par1 to $1 … par4 to $4
97
SL C/UNI X/JU LY200 LY2000 0
Passing command line arguments •
To write a shell by name sh02 which copies one file to another
echo Copying $1 to $2 cp $1 $2 $2 •
By executing sh02
$sh02 file1 file2 Copying file1 to file2. •
Positional parameters can not assigned values
like $1=100 98
SL C/UNI X/JU LY200 LY2000 0
Shell Variables •
To know the number of variables given for the shell through $#
$abc file1 file echo $# $# •
The above shell displays 3
99
SL C/UNI X/JU LY200 LY2000 0
Shell Variables - shift •
Shell can handle only 9 variables at a time. To access more than 9, the shift command is used
•
$set You have the learn the shell programming in acapacity very easytoway •
•
•
$echo $10 displays You0 as shell interprets $10 as $1 with 0. $shift 5 : makes the 5th argument as $1 argument. Thus $echo $1 displays learn
•
$* handles all positional parameters
100
SL C/UNI X/JU LY200 LY2000 0
Positional Parameters Positional Parameters If the number of parameters are greater than nine shift command The shift The command can be used to shift the parameters For Example : $ set a b c d e f g h i j k l m n o p $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 a b c d e f g h i
$ shift 7 $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 h I j k l m n o p
Anything after „# „#‟ sign will be treated as comment expr is the key word for doing arithmetic expr is A multiplication symbol (* (*) should be preceded by „\ „\‟ Terms in expr should be separated by space Parenthesis may be used for clarity of
expression 104
SL C/UNI X/JU LY200 LY2000 0
Arithmetic in Shell •
Arithmetic in shell scripts –
–
The expr can be used only for integers For Floating point the command bc is used
# example of floating point arithmetic program a=15.5 b=7.8 c=„echo $a + $b | bc„ (returns 23.3) 23.3) d=„echo $a - $b | bc„ (returns 7.7) 7.7) e=„echo $a \* $b | bc„ bc„ (returns 120.9) 120.9)
f=„echo $a / $b | bc„
(returns 1) 1)
105
SL C/UNI X/JU LY200 LY2000 0
UNIX decision loops •
There are 4 decision making loops
if then fi if then else fi if then elif else fi case - esac
106
SL C/UNI X/JU LY200 LY2000 0
UNIX - if then fi •
Key word if and the delimiter is „fi „fi‟‟
if <command> then statements fi e.g.: if cp $1 $2 then echo “Copied successfully” successfully”
fi 107
SL C/UNI X/JU LY200 LY2000 0
UNIX - if then else fi •
The structure of this construct is:
if <Condition> then statements else statements fi
108
SL C/UNI X/JU LY200 LY2000 0
UNIX - if then else fi e.g.:
if cp $1 $2 then echo File copied successfully else echo File copy failed
fi 109
SL C/UNI X/JU LY200 LY2000 0
else - fi” fi” Example “if – else # Example of numeric test echo Enter basic salary read bs if [ $bs -lt 2500 ] then hra=„echo $bs \* 10 / 100 | bc„ bc„ da=„echo $bs \* 90 / 100 bc„ bc„ else hra=500 da=„echo $bs \* 98 / 100 | bc„ bc„ fi gs=„echo $bs + $hra + $da | bc„ bc„
echo Gross salary = Rs. $gs 110
SL C/UNI X/JU LY200 LY2000 0
UNIX - if then elif else fi •
Used for multilevel decision making.
if <condition> then statements elif <condition> statements else statements
fi 111
SL C/UNI X/JU LY200 LY2000 0
UNIX - test •
•
if depends upon the exit status of the command given test verbs translates the result into success or failure
•
There are three tests namely
•
Numerical test
•
String test
File test 112
SL C/UNI X/JU LY200 LY2000 0
UNIX - test - numerical •
Used to compare numerical
-gt gt = = greater than -lt lt = less than -ge ge = = greater than or equal to -le le = less than or equal to -ne ne = = not equal -eq eq = = equal
113
SL C/UNI X/JU LY200 LY2000 0
UNIX - test - numerical if [ $1 -lt 5 ] then echo the value is < 5 elif [ $1 -le 7 ] echo the value is <= or equal 7 else echo the value is > 7 fi
114
SL C/UNI X/JU LY200 LY2000 0
UNIX - test •
Use square braces to avoid writing test
•
Provide a space after „[ „[„
•
Provide a space before „] „]‟
115
SL C/UNI X/JU LY200 LY2000 0
UNIX - test - file •
The following are the file related flags
•
-s returns True if the file exists and size > 0
•
•
-f returns returns True if the file exists and not directory
-d return True if the file exists and is a directory
e.g.: if [ -f $1 ] then
echo File exists fi 116
SL C/UNI X/JU LY200 LY2000 0
UNIX - test - String •
s1 = s2 returns true if both are same
•
-n returns true if string length > 0
if [ $1 = $2 ] then echo Both strings are same else fi •
echo $?
$? Contains $? Contains the value of the last command
•
0 = true, 1 = false
117
SL C/UNI X/JU LY200 LY2000 0
UNIX logical conditions •
-a stands for AND condition
•
-o stands for OR condition
•
-! Is negation
•
if <Condition-1> -a <Condition-2>
•
Returns true if both the conditions are true if [ $1 -gt 60 ] -a [ $2 -lt 50 ] then
statements... statements ... 118
SL C/UNI X/JU LY200 LY2000 0
UNIX case •
To handle multiple choices
•
case value case value in
•
choice 1) statements;;
•
choice 2) statements;;
•
•
*) statements;; esac esac
119
SL C/UNI X/JU LY200 LY2000 0
UNIX case •
esac is the delimiter of case
•
Used for menus
•
*) is the default choice
•
All choice statements should be terminated by double semicolon(;;)
120
SL C/UNI X/JU LY200 LY2000 0
UNIX case example case $option in 1) echo Financial accounting;; 2) echo Materiel accounting;; *) echo Invalid Opt - Try;; esac
121
SL C/UNI X/JU LY200 LY2000 0
UNIX case •
The choices many be in any order
•
case statement may be a shell variable or
•
shell argument or output of a command co mmand Need not be numbers - may be strings too to o
e.g.: case $1 in banana | orange) echo Fruit;; dog | pig) echo Animal;; lion) echo Wild animal;; esac
123
SL C/UNI X/JU LY200 LY2000 0
UNIX case •
Can use shell‟s pattern matching matching
e.g.:
case $1 in [a-z]) echo Small alpha;; [A-Z]) echo Capital;; esac
124
SL C/UNI X/JU LY200 LY2000 0
UNIX Loop Controls •
Provided 3 loop constructs namely:
•
while loop
•
f or loop
•
until loop loop
125
SL C/UNI X/JU LY200 LY2000 0
UNIX - while loop while <condition> <condition> do statements done
•
done is the delimiter of do
126
SL C/UNI X/JU LY200 LY2000 0
UNIX - while example count = 1 while [ $count -le 3 ] do echo Loop value $count count = `expr $count + 1` done
127
SL C/UNI X/JU LY200 LY2000 0
loop Examples of “while” loop # calculation of simple interest count=1 while [ $count -le 3 ] do echo “\nEnter “\nEnter p,n,r\c” p,n,r\c” read p n r si=„echo $p \* $n \* \* $r /100 | bc„ bc„ echo Simple interest = Rs.$si count=„expr $count + 1„ 1„ done
# printing numbers using while i=1 while [ $i -le 10 ] do echo $i i=„expr $i + 1„ 1„
done
128
SL C/UNI X/JU LY200 LY2000 0
UNIX - while •
•
•
The loop will continue so long as the condition is TRUE When the condition is false, the next command after done will be executed The condition can be any valid UNIX command
•
The whilecondition condition can be simple condition or complex •
The condition should have an exit status. Otherwise, it may go into infinite loop
129
SL C/UNI X/JU LY200 LY2000 0
UNIX - until loop until <condition> do statements done •
until continues its loop so long as the condition is false •
except this, while & until are identical
130
SL C/UNI X/JU LY200 LY2000 0
Example - until loop
# printing numbers using until i=1 until [ $i -gt 10 ] do echo $1 i=„expr $i + 1„ 1„ done
131
SL C/UNI X/JU LY200 LY2000 0
UNIX - for loop •
Most frequently used loop
for control-var in value1 value2… value2… do statements done •
for takes a list of variables
132
SL C/UNI X/JU LY200 LY2000 0
UNIX - for example for word in $* do echo $word done
133
SL C/UNI X/JU LY200 LY2000 0
Example Example – – for for loop Example # To print names of all sub-directories for entry in * do if [ -d $entry ] then echo $entry fi done
134
SL C/UNI X/JU LY200 LY2000 0
UNIX - break statement •
Used to break the current loop and comes out of the loop
Usually associated with i f if [ $1 -eq 5 ] •
then I = 2 break
fi 135
SL C/UNI X/JU LY200 LY2000 0
UNIX - continue statement •
To take the control to the beginning of the loop bypassing the statements
I=1 while [ $I -le 5 ] then do I = `expr $I + 1` continue
done 136
SL C/UNI X/JU LY200 LY2000 0
UNIX - Metacharacters •
Called as regular expressions.
•
Classified as follows:
File name
: ? * […] [!…] [!…]
I/O redirection
: < > >> << m> m>&n m>&n
Process execution: ; ( ) & && || || Positional paras : $1..$9 $1..$9 Spl characters
: $0 $* $@ $# $! $$ $- $-
137
SL C/UNI X/JU LY200 LY2000 0
UNIX - File name •
ls ?? ls ?? - lists all files with 2 chars long
•
ls a* ls a* - lists all file names begin with a
•
ls [a-c]* ls [a-c]* -file -file names begin with a,b &c
•
ls [!a-c] ls [!a-c] - file names not starting with a,b,c
138
SL C/UNI X/JU LY200 LY2000 0
UNIX - I/O Redirection •
< - take input from
•
> write output to
•
>> append >> append output
•
•
<< abc << abc - takes the input till „abc‟ encountered m> filename filename - Makes filename as output of m
•
139
m<& <&n n - Merges stdin, stdout and stderr SL C/UNI X/JU LY200 LY2000 0
UNIX - Process Execution •
; - multiple commands separated by „;‟ „;‟
•
& - puts to background process
•
•
&& means AND - Comd1 && Comd2 && means Co md2 : Executes Comd2 if and only if Comd1 is successful || means OR - Comd1 || Comd2 - Executes || means Comd2 if Comd1 fails
140
SL C/UNI X/JU LY200 LY2000 0
UNIX - Special Characters •
•
•
•
•
$$ $$ - Gives the Process id of the command $? - Exit status of the last executed $? command $! $! - PID of last background process $# - Total number of positional $# parameters $0 $0 - Command name
•
141
$* $* - list all shell arguments SL C/UNI X/JU LY200 LY2000 0
Tips & Traps •
•
•
Try to use the absolute abso lute paths in the shell scripts. This saves the search time of the system for the command Remove write permissions to files that are important. This even prevents the accidental update of the files Compress the print/report files. These
files occupies lot of disk space. Better pack them and keep 142
SL C/UNI X/JU LY200 LY2000 0
Tips & Traps •
The compressed print files can be printed directly without uncompress them by
using the pcat command pcat textfile.txt.z $pcat textfile.txt.z > /dev/lp0 •
The above command will send the print file directly to printer
143
SL C/UNI X/JU LY200 LY2000 0
Tips & Traps •
•
•
•
Untouched files in the directory may be found using find command. command. $find . -mtime 10 -print displays the files that are untouched for the last 10 days Clean up of the directory should be done periodically. Otherwise, any amount disk