Chapter 6: Shell Programming

41
Chapter 6: Shell Programming Shell Scripts

description

Chapter 6: Shell Programming. Shell Scripts. Using the UNIX Shell as a Programming Objectives:. After studying this lesson, you should be able to: Learn about shell variables, operators Write simple shell scripts to illustrate programming logic. My first Shell Script. vi myfirstscript.sh - PowerPoint PPT Presentation

Transcript of Chapter 6: Shell Programming

Page 1: Chapter 6:  Shell Programming

Chapter 6: Shell Programming

Shell Scripts

Page 2: Chapter 6:  Shell Programming

Using the UNIX Shell as a Programming Objectives:

• After studying this lesson, you should be able to:

–Learn about shell variables, operators

–Write simple shell scripts to illustrate programming logic

Page 3: Chapter 6:  Shell Programming

My first Shell Script

• vi myfirstscript.sh

#! /bin/cshset directory=`pwd`

echo The date today is `date`

echo The current directory is $directory

• chmod u+x myfirstscript.sh

• myfirstscript.sh

Page 4: Chapter 6:  Shell Programming

Using UNIX Shell Scripts

• UNIX shell scripts are text files that contain sequences of UNIX commands

• Like high-level source files, a programmer creates shell scripts with a text editor

• Shell scripts do not have to be converted into machine language by a compiler

• This is because the UNIX shell acts as an interpreter when reading script files

Page 5: Chapter 6:  Shell Programming

Using UNIX Shell Scripts Continued

• As an interpreter reads the statements in a program file, it immediately translates them into executable instructions, and causes them to run

• After you create a shell script, you simply tell the operating system that the file is a program that can be executed

• This is accomplished by using the chmod command to change the files’ mode

Page 6: Chapter 6:  Shell Programming

Using UNIX Shell Scripts Continued

• Further, the chmod command tells the computer who is allowed to use the file: the owner (u), the group (g), or all other users (o)

• Shell programs run less quickly than do compiled programs, because the shell must interpret each UNIX command inside the executable script file before it is executed

Page 7: Chapter 6:  Shell Programming

The Programming Shell

Commonly used shell in most variant of UNIX are: • Bourne Shell (sh), first shell developed for UNIX • Bourne Again Shell (bash), written by programmers

of Free Software Foundation, open source shell from GNU

• Korn Shell (ksh), written by David Korn, superset of Bourne shell, not widely distributed.

• C Shell (csh), written by Bill Joy, the author of vi, shared much of the C language structure.

• Terminal Based C Shell (tcsh), enhanced version of the Berkeley UNIX C shell csh

Page 8: Chapter 6:  Shell Programming

The Programming Shell

• All Linux versions use the Bash shell (Bourne Again Shell) as the default shell

• All UNIX system include C shell and its predecessor Bourne shell.

Page 9: Chapter 6:  Shell Programming

Shell Programming

• programming features of the UNIX shell:

Shell variablesShell variables

OperatorsOperators

Logic structuresLogic structures

Page 10: Chapter 6:  Shell Programming

Shell Programming

• programming features of the UNIX shell: Shell variablesShell variables: Your scripts often need to keep values

in memory for later use. Shell variables are symbolic names that can access values stored in memory

OperatorsOperators: Shell scripts support many operators, including those for performing mathematical operations

Logic structuresLogic structures: Shell scripts support sequential logic (for performing a series of commands), decision logic (for branching from one point in a script to another), looping logic (for repeating a command several times), and case logic (for choosing an action from several possible alternatives)

Page 11: Chapter 6:  Shell Programming

Shell Programming

• programming features of the UNIX shell:

Shell variablesShell variables

OperatorsOperators

Logic structuresLogic structures

Page 12: Chapter 6:  Shell Programming

Variables

• Variables are symbolic names that represent values stored in memory

• The three types of variables discussed in this section are configuration variables, environment variables, and shell variables

• Use configuration variables to store information about the setup of the operating system, and do not change them

• You can set up environment variables with initial values that you can change as needed

Page 13: Chapter 6:  Shell Programming

Variables Continued

• These variables, which UNIX reads when you log in, determine many characteristics of your session

• Shell variables are those you create at the command line or in a shell script

• Environment and configuration variables bear standard names, such as HOME, PATH, SHELL, USERNAME, and PWD

• (Configuration and environment variables are capitalized to distinguish them from user variables)

Page 14: Chapter 6:  Shell Programming

Variables Continued

To see a list of your environment variables:

$ printenv

or:

$ printenv | more

Page 15: Chapter 6:  Shell Programming

Variables Continued

1. Typical Environment Variables– HOME: pathname of your home directory– PATH: directories where shell is to look

for commands– USER: your user name– PWD: your current working directory– MAIL: pathname of your system mailbox– SHELL: pathname of your shell

2. Variable contents are accessed using ‘$’:e.g. $ echo $HOME

Page 16: Chapter 6:  Shell Programming

Variables Continued

• A shell variable take on the generalized form variable=value (except in the C shell).

$ x=37; echo $x$ 37$ unset x; echo $x

• The C shell uses the set statement set variables.

$ set x = 37• You can set a pathname or a command to a

variable or substitute to set the variable.$ set mydir=`pwd`; echo $mydir

Page 17: Chapter 6:  Shell Programming

Variables Continued

• To create lists:$ set Y = (UNL 123 CS251)

• To set a list element:$ set Y[2] = HUSKER

• To view a list element:$ echo $Y[2]

Page 18: Chapter 6:  Shell Programming

Variables Continued

• vi myinputs.sh#! /bin/cshecho Total number of inputs: $#argvecho First input: $argv[1]echo Second input: $argv[2]

• chmod u+x myinputs.sh• myinputs.sh HUSKER UNL CSE

Page 19: Chapter 6:  Shell Programming

Shell Programming

• programming features of the UNIX shell:

Shell variablesShell variables

OperatorsOperators

Logic structuresLogic structures

Page 20: Chapter 6:  Shell Programming

Shell Operators

• The Bash shell operators are divided into three groups: defining and evaluating operators, arithmetic operators, and redirecting and piping operators

Page 21: Chapter 6:  Shell Programming

Arithmetic Operators

• expr supports the following operators:– arithmetic operators: +,-,*,/,%– comparison operators: <, <=, ==, !=, >=, >– boolean/logical operators: &, |– parentheses: (, )– precedence is the same as C, Java

Page 22: Chapter 6:  Shell Programming

Arithmetic Operators (example)

• vi math.sh

#!/bin/csh

set count=5

set count=`expr $count + 1`

echo $count

• chmod u+x math.sh

• math.sh

Page 23: Chapter 6:  Shell Programming

Shell Programming

• programming features of the UNIX shell:

Shell variablesShell variables

OperatorsOperators

Logic structuresLogic structures

Page 24: Chapter 6:  Shell Programming

Shell Logic Structures

The four basic logic structures needed for

program development are:

Sequential logic

Decision logic

Looping logic

Case logic

Page 25: Chapter 6:  Shell Programming

Sequential Logic

• Sequential logic states that commands

will be executed in the order in which they

appear in the program

• The only break in this sequence comes

when a branch instruction changes the

flow of execution

Page 26: Chapter 6:  Shell Programming

Decision Logic

• Decision logic enables your program to execute a statement or series of statements only if a certain condition exists

• The if statement is the primary decision-making control structure in this type of logic

Page 27: Chapter 6:  Shell Programming

Decision Logic (continued)

• if-then

if ( expr ) simple-command

• if-then-elseif ( expr ) then

command-set-1[else

command-set-2]endif

Page 28: Chapter 6:  Shell Programming

Decision Logic (continued)

• A simple example

#!/bin/cshif ($#argv != 2) then echo $0 needs two parameters! echo You are inputting $#argv parameters.else set par1 = $argv[1] set par2 = $argv[2]endif

Page 29: Chapter 6:  Shell Programming

Decision Logic (continued)

Another example:#! /bin/csh# number is positive, zero or negativeecho "enter a number:"set number = $<if ( $number < 0 ) then

echo "negative"else if ( $number == 0 ) then

echo zeroelse echo positiveendif

Page 30: Chapter 6:  Shell Programming

Decision Logic (continued)

Another example:

#!/bin/cshif {( grep UNIX $argv[1] > /dev/null )} then

echo UNIX occurs in $argv[1]else echo No! echo UNIX does not occur in

$argv[1]endif

Redirect intermediate results into >/dev/null, instead of showing on the screen.

Page 31: Chapter 6:  Shell Programming

Looping Logic

• In looping logic, a control structure (or loop) repeats until some condition exists or some action occurs

• You will learn two looping mechanisms in this section: the for loop and the while loop

• You use the for command for looping through a range of values.

• It causes a variable to take on each value in a specified set, one at a time, and perform some action while the variable contains each individual value

Page 32: Chapter 6:  Shell Programming

The while Loop

• A different pattern for looping is created using the while statement

• The while statement best illustrates how to set up a loop to test repeatedly for a matching condition

• The while loop tests an expression in a manner similar to the if statement

• As long as the statement inside the brackets is true, the statements inside the do and done statements repeat

Page 33: Chapter 6:  Shell Programming

Looping Logic

while ( expr )

command_set

end

foreach var ( worddlist )

command_set

end

Page 34: Chapter 6:  Shell Programming

Looping Logic

Program:

#!/bin/cshforeach person (Bob Susan Joe Gerry)

echo Hello $personend

Output:Hello BobHello SusanHello JoeHello Gerry

Page 35: Chapter 6:  Shell Programming

Looping Logic

• Adding integers from 1 to 10

#!/bin/cshset i=1set sum=0while ($i <= 10)

echo Adding $i into the sum. set sum=`expr $sum + $i` set i=`expr $i + 1`

endecho The sum is $sum.

Page 36: Chapter 6:  Shell Programming

Switch Logic

• The switch logic structure simplifies the selection of a match when you have a list of choices

• It allows your program to perform one of many actions, depending upon the value of a variable

Page 37: Chapter 6:  Shell Programming

Switch Logic

switch ( var )case string1:

command_set_1breaksw

case string2:command_set_2breaksw

defaultcommand_set_3

endsw

Page 38: Chapter 6:  Shell Programming

Switch Logic

#!/bin/csh

if ($#argv == 0 ) then

echo "No arguments supplied...exiting"

else

switch ($argv[1])

case [yY]:

echo Argument one is yes.

breaksw

case [nN]:

echo Argument one is no.

breaksw

default:

echo Argument one is neither yes nor no.

breaksw

endsw

endif

Page 39: Chapter 6:  Shell Programming

Chapter Summary

• A high-level language must be converted into a low-level (machine) language before the computer can execute it

• The shell interprets UNIX shell scripts• UNIX shell scripts, created with the vi or other

editor, contain instructions that do not need to be written from scratch, but rather can be selectively chosen from the operating system’s inventory of executable commands

Page 40: Chapter 6:  Shell Programming

Chapter Summary Section A Continued

• Linux shells are derived from the UNIX Bourne, Korn, and C shells

• UNIX keeps three types of variables:

– Configuration

– Environment

– Shell

• The shell supports numerous operators, including many for performing arithmetic operations

• The logic structures supported by the shell are sequential, decision, looping, and case

Page 41: Chapter 6:  Shell Programming

Homework 1

• Please refer to handout.