Beruflich Dokumente
Kultur Dokumente
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.
Shell Programming. To understand Types of Shells. Shell Variables. Programming Constructs. System Variables Customizing the shell To understand Commands related to File Handling.
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).
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.
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.
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.
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
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
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.
10
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.
11
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
12
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
13
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
14
$> 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 [ ].
15
15
16
$> 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
17
$> str1="Infosys" $> str2="Infy" $> test $str1 = $str2 $> echo $? 1 strings are different. # indicates both the
17
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.
18
$> 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
19
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
20
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.
21
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
22
$> 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
23
23
if statement.
Syntax.
if control command then <commands> else <commands> fi
24
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.
25
$> 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.
26
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.
27
$> 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.
28
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
continue
To jump to the start of loop.
exit
To prematurely terminate a program.
: or #
To interpret the rest of line as comments.
29
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
30
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.
31
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
32
/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
PS2
Used for changing the secondary prompt.
33
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
34
Example $> set 12 23 34 set command. $> echo $1 12 $> echo $2 23 $> echo $3 34
$> 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
du
Prints the disk usage. du [OPTIONS] [FILE]
36
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
File Type determination. file [OPTIONS] FILES
37
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
touch.
Updates the access and modification times. touch [-amc] [mmddhhmm[yy]] files
38
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.
39
39
Thank You!
Copyright 2004, Infosys Technologies Ltd 40 ER/CORP/CRS/OS31/003 Version No: 2.00
40