Sie sind auf Seite 1von 40

Unix

Programming with the Shell.

Welcome to this course on Unix Operating System, Day 2.

Road Map
Recap of Day 1 To understand the types of shell. To understand Shell variables. To understand the programming constructs. To understand the System Variables. To customize the shell. To understand Commands related to File Handling.

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

Shell Programming. To understand Types of Shells. Shell Variables. Programming Constructs. System Variables Customizing the shell To understand Commands related to File Handling.

Shell Types in Unix


Bourne Shell. Bourne Again Shell (bash). C Shell (c-shell). Korn Shell (k-shell). TC Shell (tcsh)

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

Bourne shell (/bin/sh) This is the original Unix shell written by Steve Bourne of Bell Labs. It is available on all UNIX systems. This shell does not have the interactive facilities provided by modern shells such as the C shell and Korn shell. The Bourne shell does provide an easy to use language with which you can write scripts. Bourne again shell (/bin/bash) written by the Free Software Foundation. This shell is widely used within the academic community. bash provides all the interactive features of the C shell (csh) and the Korn shell (ksh). Its programming language is compatible with the Bourne shell (sh).

Shell Types in Unix (Contd)


Please see the notes page for an explanation of the earlier slide

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

C shell (/bin/csh) This shell was written at the University of California, Berkeley. It provides a C-like language with which to write shell scripts. Korn shell, /bin/ksh, David Korn (Bell Labs) This shell was written by David Korn of Bell labs. It is now provided as the standard shell on Unix systems. It provides all the features of the C and TC shells together with a shell programming language similar to that of the original Bourne shell. TC Shell (tcsh) It provides all the features of the C shell together with emacs style editing of the command line. References http://unixhelp.ed.ac.uk/

The Shell.
A program that interprets users requests to run programs. Provides environment for user programs. A command line interpreter that Reads user inputs. Executes commands.

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

Ask the audience to come out with the different functions and uses of shell, covered in Chapter 1. Shell acts as an interpreter for users requests.

The Shell.
Shell allows three types of commands:
An internal command. An executable file that contains a sequence of shell command lines. An executable file that contains object code produced by compilation.

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

Three types of commands are allowed in Unix: 1) An internal command refers to the vast library of in-built commands. Example : cal, cat, etc. 2) An executable file could be a file created by a user for a particular application, which contains various commands. It is always advisable to have an extension of .sh for the user-program. A program in Unix created by the user is called as Shell Script. 3) An executable file whose source code could be statement written in languages like C, etc.

Shell Features.
Interactive and background processing. Input/output redirection Pipes. Wild card matching. Programmable.
Shell Variables. Programming language constructs. Shell Scripts.

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

Shell allows execution of tasks in the background by putting an & sign. Example $> sleep 100 Output : For a period of 100 seconds, the terminal would be idle and user cannot work. $> sleep 100 & # & is used for placing the process in the background. [1] 32389 # PID of the process which has been put in the background. Output : The command is executed in the background. The user could work on another job. Shell allows the user to work with pipes, wherein the user can redirect commands. Shell allows the user to work with Wild Cards, wherein the user can select multiple files. The user could write programs based on the users application.

Shell Variables.
Positional Parameters. Special Parameters. Named variables

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

In shell programming, we deal with three basic types of variables . Positional parameters Special parameters Named variables

Positional Parameters.
Acquire values from the position of arguments in command line.
$1, $2, $3,..$9 sh file1 10 20 30

$1 $2 $3

Copyright 2004, Infosys Technologies Ltd

ER/CORP/CRS/OS31/003 Version No: 2.00

Acquire values from the position of arguments in command line. Example: $ cat>data1 echo Your marks in Sem1 is : $1 echo Your marks in Sem2 is : $2 echo Your marks in Sem3 is : $3 {ctrl - d} $ sh data1 10 20 30 Your marks in Sem1 is : 10 Your marks in Sem2 is : 20 Your marks in Sem3 is : 30

Special Parameters.
Shell assigns the value for this parameter.
$$ - PID number. $# - Number of Command Line Arguments. $0 Command Name. $* - Displays all the command line arguments. $? Exit Status. $- - Shell options $! - Process number of the last background command $@ - Same as $*, except when enclosed in double quotes.

Copyright 2004, Infosys Technologies Ltd

10

ER/CORP/CRS/OS31/003 Version No: 2.00

Shell assigns the value for the special parameter. symbol $$ (PID) of the current shell $# positional parameters while invoking the shell script $0 command being executed $* parameters $? executed command $$! of the last background command $@ when enclosed in double quotes Example $> echo $$ 32344 the users shell. #Displays the PID of meaning The process number The number of The name of the The list of positional Exit status of the last Shell options The process number Same as $*, except

10

Named Variables.
User-defined variable that can be assigned a value. Used extensively in shell-scripts. Used for reading data, storing and displaying it.

Copyright 2004, Infosys Technologies Ltd

11

ER/CORP/CRS/OS31/003 Version No: 2.00

Named variables A named variable is a user-defined variable that can be assigned a value within a Shell program. The value of a named variable can be retrieved by preceding the variable name with a $ sign Example: $ x1=10 $ echo $x1 10

11

Accepting Data.
read. Accepts input from the user. Syntax : read variable_name. Example : read sname

Variable Name

Copyright 2004, Infosys Technologies Ltd

12

ER/CORP/CRS/OS31/003 Version No: 2.00

In shell scripts , read is used for accepting data from the user and storing it for other processing.

12

Display Data.
echo
Used to display a message or any data as required by the user. echo [Message, Variable] Example: echo Infosys Technologies Ltd. echo $sname

Variable Name

Copyright 2004, Infosys Technologies Ltd

13

ER/CORP/CRS/OS31/003 Version No: 2.00

Echo is used for displaying data. This data could be either a data inside the variable or any message.

13

Program Execution.
sh
Command to execute program in Unix. Syntax : sh <Shell Script Name> Example : sh file1

Copyright 2004, Infosys Technologies Ltd

14

ER/CORP/CRS/OS31/003 Version No: 2.00

$> cat>file1 echo "Enter your name" read sname echo "Your name is "$sname {ctrl-d} $> sh file1 Enter your name Ajit Your name is Ajit Here the value of name is stored in the variable sname. If a file does not have an executable permission, then the file could be executed using the . Operator. Example $> . file1.sh #Executes the file named file1.sh

If a file has an executable permission, then the file could be executed only by calling its name. Example $> file1.sh #Executes the file named file1.sh

14

test command.
Used extensively for evaluating shell script conditions. It evaluates the condition on its right and returns a true or false exit status. The return value is used by the construct for further execution. In place of writing test explicitly, the user could also use [ ].

Copyright 2004, Infosys Technologies Ltd

15

ER/CORP/CRS/OS31/003 Version No: 2.00

15

test command (Contd).


Operators used with test for evaluating numeral data are: -eq -lt -le -gt -ge -le Equal To Less than Less than Greater than Greater than or equal to Less than or equal to

Copyright 2004, Infosys Technologies Ltd

16

ER/CORP/CRS/OS31/003 Version No: 2.00

$> a1=10 $> a2=20 $> test $a1 -eq $a2 $> echo $? 1 Instead of test command, we could also use [ ] $> a1=10 $> a2=20 $> [ $a1 -eq $a2 ] $> echo $? 1 Note : A space is mandatory after [ and before ].

16

test command (Contd).


Operators used with test for evaluating string data are:

str1 = str2 str1 != str2 -n str1 -z str1

True if both equals True if not equals

True if str1 is not a null string True if str1 is a null string

Copyright 2004, Infosys Technologies Ltd

17

ER/CORP/CRS/OS31/003 Version No: 2.00

$> str1="Infosys" $> str2="Infy" $> test $str1 = $str2 $> echo $? 1 strings are different. # indicates both the

17

test command (Contd).


Operators used with test for evaluating file data are:

-f file1 -d file1 -s file1 -r file1 -w file1 -x file1

True if file1 exists and is a regular file. True if file1 exists and is directory. True if file1 exists and has size greater than 0 True if file1 exists and is readable. True if file1 exists and is writable. True if file1 exists and is executable.

Copyright 2004, Infosys Technologies Ltd

18

ER/CORP/CRS/OS31/003 Version No: 2.00

$> test -f grt1 $> echo $? 0 regular file. #indicates the file by name grt1 exists and is

18

Logical Operators.
Logical Operators used with test are:

! -a -o

Negates the expression. Binary and operator. Binary or operator.

Copyright 2004, Infosys Technologies Ltd

19

ER/CORP/CRS/OS31/003 Version No: 2.00

Logical operations Examples: $> cat>pr1.sh x=10; if test $x -lt 15 -o $x -gt 5 than 15. then echo "Correct" else echo "Wrong" fi {ctrl-d} Output Correct. #Checks for value of x greater than 5 or less

19

Shell Quotes-Meanings.
(single forward quotes)
'....' take .... Literally

` (single backward quotes)


`` to be interpreted by shell

" " (double quotes)


"...." take .... literally after $.

Copyright 2004, Infosys Technologies Ltd

20

ER/CORP/CRS/OS31/003 Version No: 2.00

Examples: $> x=10 $> echo 'echo $x echo $x used. $> echo `echo $x` 10 quote is used. $> echo "echo $x" echo 10 used. #Output when double quote is #Output when single backward #Output when single quote is

20

expr command.
Used for evaluating shell expressions. Used for arithmetic and string operations.
Example : expr 7 + 3 would give an output 10.
Operator has to be preceded and followed by a space.

When used with variables, back quotes need to be used.

Copyright 2004, Infosys Technologies Ltd

21

ER/CORP/CRS/OS31/003 Version No: 2.00

$> x=10 $> y=20 $> z=`expr $x + $y` $> echo $z 30

21

Conditional Execution.
&&
The second command is executed only when first is successful. command1 && command2

||
The second command is executed only when the first is unsuccessful. command1 || command2

Copyright 2004, Infosys Technologies Ltd

22

ER/CORP/CRS/OS31/003 Version No: 2.00

$> cat file2 8000 9000 7000 $> grep 9000 file2 && echo "Correct" 9000 Correct $> grep 2000 file2 || echo "Wrong" Wrong

22

Program Constructs
if for while until case

Copyright 2004, Infosys Technologies Ltd

23

ER/CORP/CRS/OS31/003 Version No: 2.00

23

if statement.
Syntax.
if control command then <commands> else <commands> fi

Copyright 2004, Infosys Technologies Ltd

24

ER/CORP/CRS/OS31/003 Version No: 2.00

Example: echo "Enter a number" read num if test $num -le 30 then echo "Number is less than or equal to 30" else echo "Number is greater than 30" fi Output: If the user gives a number less than or equal to 30 , then the output would be Number is less than or equal to 30, else the output would be Number is greater than 30.

24

for statement.
Syntax.

for variable-name in value1 value2 .... do <commands> done

Copyright 2004, Infosys Technologies Ltd

25

ER/CORP/CRS/OS31/003 Version No: 2.00

$> cat grt1 for x in 1 2 3 6 do echo "$x" done {ctrl-d} $> sh grt1 1 2 3 6

25

while statement.
Syntax.

while control command do <commands> done

Copyright 2004, Infosys Technologies Ltd

26

ER/CORP/CRS/OS31/003 Version No: 2.00

Example: $> cat > grt2 x=1 while test $x -le 6 do echo "$x" x=` expr $x + 1 ` done {ctrl-d} $> sh grt2 1 2 3 4 5 6

26

until statement.
Syntax.

until control command do <commands> done

Copyright 2004, Infosys Technologies Ltd

27

ER/CORP/CRS/OS31/003 Version No: 2.00

$> cat>grt3 x=1 until test $x -ge 6 do echo "$x" x=` expr $x + 1 ` done {ctrl-d} $> sh grt3 1 2 3 4 5

27

case statement.
Syntax.
The symbols ;; are used as option terminators.

case value in choice1) commands ;; choice2) commands ;; .... .... esac

Copyright 2004, Infosys Technologies Ltd

28

ER/CORP/CRS/OS31/003 Version No: 2.00

Example: $> cat>grt5 echo "Enter the data" read data case $data in 1) echo "One";; 2) echo "Two";; 3) echo "Three";; *) echo "Greater than Three" esac {ctrl-d} Output: If the user enters any number less than 4, it displays the number in words, else it displays Greater than Three.

28

Useful Shell Scripting commands.


break
To come out of a loop.

continue
To jump to the start of loop.

exit
To prematurely terminate a program.

: or #
To interpret the rest of line as comments.

Copyright 2004, Infosys Technologies Ltd

29

ER/CORP/CRS/OS31/003 Version No: 2.00

29

Trap command.
trap
To alter the effects of certain events that generate signals, which generally tends to halt a process. Syntax: trap command signal list

Copyright 2004, Infosys Technologies Ltd

30

ER/CORP/CRS/OS31/003 Version No: 2.00

UNIX provides the trap command which allows the user to alter the effects of certain events that generate signals, which generally tend to halt a process: The hang-up signal is denoted by code number 1. The interrupt (Ctrl-C) signal is denoted by code number 2. The terminate (by kill command) is denoted by code number 15. The general form of the trap command The trap command, once it has been read in, lies in wait for those signals mentioned in the signal list. When such a signal shows up, the command is performed instead of the consequence of the signal that would have been to halt the process. Example $> cat>unix_prog1.sh trap 'echo "You cannot exit without entering data"' 2 #If user presses ^C key, it displays the message. echo "Enter your data" read data {ctrl-d} $> sh unix_prog1.sh Enter your data #Data is requested from the user. You cannot exit without entering data when requested for data. Infosys #User enters the data. Note : The signal 9 cannot be trapped. #User presses ^C

30

export command.
export
To make a variable a part of environment and also be accessible to the child shell.

Copyright 2004, Infosys Technologies Ltd

31

ER/CORP/CRS/OS31/003 Version No: 2.00

export A Shell variable can be exported so that it becomes part of the environment. A process can then access and use any of the variables in its environment. Note : An exported variable becomes part of the environment of the current shell and of all processes descending from it. Also, it is important that to make a variable accessible to all subshells, it should be defined and exported from the login shell itself. A user variable if not exported will not be visible to the subshells. Example: $> a=10 $> echo $$ 6034 $> echo $a 10 $> sh $> echo $$ 9072 $>echo $a After using export $> export a $> sh $>echo $a 10 #Creates a child shell #Creates a child shell #PID of child shell #PID of the shell

31

System Variables.
PATH
Search path referred by Unix for any command. echo $PATH

HOME
Indicates the home directory for the user. echo $HOME

Copyright 2004, Infosys Technologies Ltd

32

ER/CORP/CRS/OS31/003 Version No: 2.00

$> echo $PATH

#To display the PATH

/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/ajit:. $> PATH=$PATH:/home $> echo $PATH /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/ajit:.:/home HOME $> echo $HOME /home/ajit #To display the home directory. #To append to the existing path.

32

System Variables (Contd).


PS1
Used for displaying & changing the primary prompt. echo $PS1

PS2
Used for changing the secondary prompt.

Copyright 2004, Infosys Technologies Ltd

33

ER/CORP/CRS/OS31/003 Version No: 2.00

PS1 Example $> PS1=Infosys> primary prompt. Infosys> #The prompt changes to Infosys. PS2 Example $> PS2=* #The secondary prompt changes to *. #To change the

33

set command.
set command
Used for display all the environment variables. Shows the current values of system variables. Also allows conversion of arguments into positional parameters. Syntax : set

Copyright 2004, Infosys Technologies Ltd

34

ER/CORP/CRS/OS31/003 Version No: 2.00

Example $> set 12 23 34 set command. $> echo $1 12 $> echo $2 23 $> echo $3 34

#The data 12, 23 and 34 are arguments for

$> set # set command, used without any arguments, will display the environmental variables. BASH=/bin/bash BASH_VERSINFO=([0]="2" [1]="05b" [2]="0" [3]="1" [4]="release" [5]="i386-redhatlinux-gnu") BASH_VERSION='2.05b.0(1)-release' COLORS=/etc/DIR_COLORS COLUMNS=80 DIRSTACK=() EUID=538 GROUPS=() G_BROKEN_FILENAMES=1 PATH=/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/ajit/bin:/home/ajit:. PIPESTATUS=([0]="0") PPID=331 PS1='[\u@\h \W]\$ ' PS2='> ' PS4='+ ' PVM_ROOT=/usr/share/pvm3 PVM_RSH=/usr/bin/rsh PWD=/home/ajit

34

Unix.
File Handling Commands.

35

File Handling Commands.


ulimit
Prints the value of resource limits. ulimit [OPTIONS] [N]

du
Prints the disk usage. du [OPTIONS] [FILE]

Copyright 2004, Infosys Technologies Ltd

36

ER/CORP/CRS/OS31/003 Version No: 2.00

ulimit - Prints the value of resource limits. Print the value of one or more resource limits, or, if n is specified, set a resource limit to n. Resource limits can be either hard (-H) or soft (-S). By default, ulimit sets both limits or prints the soft limit. Options: -H limit; only privileged users can raise it. -S limit. -a -c -n du - Print disk usage. Prints the number of blocks used by each named directory and its subdirectories. Default is the current directory. Options: -a -r inaccesible -s Example: $> du s /home/data To receive the result for the entire data directory as a summary Print only the grand total for each named directory Print usage for all files, not just subdirectories Print cannot open message if a file or directory is Print all limits Maximum block size of core files Maximum file descriptor plus 1 Hard limit. Anyone can lower the hard Soft limit. Must be lower than the hard

36

File Handling Commands (Contd).


find
Search for files. find [PATH] [EXPRESSION]

file
File Type determination. file [OPTIONS] FILES

Copyright 2004, Infosys Technologies Ltd

37

ER/CORP/CRS/OS31/003 Version No: 2.00

find - Search for files. Most commonly used expressions: -mount Do not descend directories on the file systems -print Print the current file name -exec command Execute command -user uname File is owned by uname -type t File has a type of t, such as d for directory and f for file - name pattern Look for the file name of pattern -newer file File was modified more recently than file Example: $> find /home name data Output: This searches the path /home looking for the name data. $> find /home name data1 exec rm {}\; Output: This searches the path /home looking for the name data1. It removes all the occurences of the file data1.

file - File Type determination. classify the named files according to the type of data they contain. Options: -c check the format of the magic file (files argument is invalid with c) -flist Run file on the filenames in list -h Dont follow symbolic links Example: $> file prog1.c Output: Describes the file command as a C Program text.

37

File Handling Commands (Contd).


df
Prints disk free blocks. DF [OPTIONS] [NAME]

touch.
Updates the access and modification times. touch [-amc] [mmddhhmm[yy]] files

Copyright 2004, Infosys Technologies Ltd

38

ER/CORP/CRS/OS31/003 Version No: 2.00

df - Print disk free blocks. name can be a device name (eg., /dev/dsk/0s9, the directory name of a mounting point (e.g., /usr), a directory name, or a remote resource name (e.g., an RFS/ NFS resource). Options: -b Print only the number of free Kilobytes -e Print only the number of free files -f Report free blocks but not free inodes -l Report only on local file systems -t Report total allocated space as well as free space touch - updates access and modification times of a file [mm month, dd date, hh hour, mm minutes, yy year] If no time is specified, the current time is used. Option -a updates only the access time. Option -m updates only the modification time. Option -c prevents creating the file if it did not exist previously. Example: $ touch -a test.c $ touch -m 1221101395 test.c

38

Summary
Types of Shells Shell Variables Program Constructs System Variables. File Handling Commands.

Copyright 2004, Infosys Technologies Ltd

39

ER/CORP/CRS/OS31/003 Version No: 2.00

39

Thank You!
Copyright 2004, Infosys Technologies Ltd 40 ER/CORP/CRS/OS31/003 Version No: 2.00

40

Das könnte Ihnen auch gefallen