chap06book

Embed Size (px)

Citation preview

  • 7/28/2019 chap06book

    1/41

    Chapter 6: Shell Programming

    Shell Scripts

  • 7/28/2019 chap06book

    2/41

    Using the UNIX Shell as a Programming

    Objectives:

    After studying this lesson, youshould be able to:

    Learn about shell variables,operators

    Write simple shell scripts toillustrate programming logic

  • 7/28/2019 chap06book

    3/41

    My first Shell Script

    vi myfirstscript.sh

    #! /bin/csh

    set directory=`pwd`

    echo The date today is `date`

    echo The current directory is $directory

    chmod u+x myfirstscript.sh

    myfirstscript.sh

  • 7/28/2019 chap06book

    4/41

    Using UNIX Shell Scripts

    UNIX shell scripts are text files thatcontain sequences of UNIX commands

    Like high-level source files, a programmercreates 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

    interpreterwhen reading script files

  • 7/28/2019 chap06book

    5/41

    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 chmodcommand to change the files mode

  • 7/28/2019 chap06book

    6/41

    Using UNIX Shell Scripts Continued

    Further, the chmod command tells thecomputer who is allowed to use the file:

    the owner(u), the group (g), or all otherusers (o)

    Shell programs run less quickly than docompiled programs, because the shell

    must interpret each UNIX command insidethe executable script file before it isexecuted

  • 7/28/2019 chap06book

    7/41

    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 programmersof Free Software Foundation, open source shellfrom GNU

    Korn Shell (ksh), written by David Korn, superset ofBourne 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 ofthe Berkeley UNIX C shell csh

  • 7/28/2019 chap06book

    8/41

    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.

  • 7/28/2019 chap06book

    9/41

    Shell Programming

    programming features of the UNIXshell:

    Shell variables

    Operators

    Logic st ruc tures

  • 7/28/2019 chap06book

    10/41

    Shell Programming

    programming features of the UNIX shell:

    Shell variables: Your scripts often need to keep valuesin memory for later use. Shell variables are symbolic

    names that can access values stored in memory

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

    Logic struc tures: 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 severalpossible alternatives)

  • 7/28/2019 chap06book

    11/41

    Shell Programming

    programming features of the UNIXshell:

    Shell variables

    Operators

    Logic st ruc tures

  • 7/28/2019 chap06book

    12/41

    Variables

    Variables are symbolic names that representvalues stored in memory

    The three types of variables discussed in thissection are configuration variables, environmentvariables, and shell variables

    Use configuration variables to store informationabout the setup of the operating system, and do

    not change them

    You can set up environment variables with initialvalues that you can change as needed

  • 7/28/2019 chap06book

    13/41

    Variables Continued

    These variables, which UNIX reads when you log in,

    determine many characteristics of your session

    Shell variables are those you create at thecommand 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)

  • 7/28/2019 chap06book

    14/41

    Variables Continued

    To see a list of yourenvironment

    variables:

    $ printenv

    or:$ printenv | more

  • 7/28/2019 chap06book

    15/41

    Variables Continued

    1. Typical Environment Variables

    HOME: pathname of your home directory

    PATH: directories where shell is to lookfor 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

  • 7/28/2019 chap06book

    16/41

    Variables Continued

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

    $ x=37; echo $x

    $ 37$ unset x; echo $x

    The C shell uses the set statement setvariables.

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

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

  • 7/28/2019 chap06book

    17/41

    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]

  • 7/28/2019 chap06book

    18/41

    Variables Continued

    vi myinputs.sh#! /bin/csh

    echo Total number of inputs: $#argvecho First input: $argv[1]echo Second input: $argv[2]

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

  • 7/28/2019 chap06book

    19/41

    Shell Programming

    programming features of the UNIXshell:

    Shell variables

    Operators

    Logic st ruc tures

  • 7/28/2019 chap06book

    20/41

    Shell Operators

    The Bash shell operators are divided into

    three groups: defining and evaluating

    operators, arithmetic operators, and

    redirecting and piping operators

  • 7/28/2019 chap06book

    21/41

    Arithmetic Operators

    exprsupports the following operators:

    arithmetic operators: +,-,*,/,%

    comparison operators:

    boolean/logical operators: &, |

    parentheses: (, )

    precedence is the same as C, Java

  • 7/28/2019 chap06book

    22/41

    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

  • 7/28/2019 chap06book

    23/41

    Shell Programming

    programming features of the UNIXshell:

    Shell variables

    Operators

    Logic st ruc tures

  • 7/28/2019 chap06book

    24/41

    Shell Logic Structures

    The four basic logic structures needed for

    program development are:

    Sequential logic

    Decision logic

    Looping logicCase logic

  • 7/28/2019 chap06book

    25/41

    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 theflow of execution

  • 7/28/2019 chap06book

    26/41

    Decision Logic

    Decision logic enables your programto execute a statement or series of

    statements only if a certain conditionexists

    The if statement is the primary

    decision-making control structure inthis type of logic

  • 7/28/2019 chap06book

    27/41

    Decision Logic (continued)

    if-then

    if ( expr ) simple-command

    if-then-elseif ( expr ) then

    command-set-1

    [elsecommand-set-2]

    endif

  • 7/28/2019 chap06book

    28/41

    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

  • 7/28/2019 chap06book

    29/41

    Decision Logic (continued)

    Another example:#! /bin/csh# number is positive, zero or negative

    echo "enter a number:"set number = $ /dev/null )} thenecho UNIX occurs in $argv[1]

    elseecho No!

    echo UNIX does not occur in $argv[1]endif

    Redirect intermediate results into >/dev/null, instead of

    showing on the screen.

  • 7/28/2019 chap06book

    31/41

    Looping Logic

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

    You will learn two looping mechanisms in thissection: the forloop and the while loop

    You use the forcommand for looping through arange of values.

    It causes a variable to take on each value in aspecified set, one at a time, and perform someaction while the variable contains each individualvalue

  • 7/28/2019 chap06book

    32/41

    The while Loop

    A different pattern for looping is created using

    the while statement

    The while statement best illustrates how to set upa 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 istrue, the statements inside the do and done

    statements repeat

  • 7/28/2019 chap06book

    33/41

    Looping Logic

    while ( expr )

    command_set

    end

    foreach var ( worddlist )

    command_set

    end

  • 7/28/2019 chap06book

    34/41

    Looping Logic

    Program:

    #!/bin/csh

    foreach person (Bob Susan Joe Gerry)echo Hello $person

    end

    Output:Hello BobHello SusanHello JoeHello Gerry

  • 7/28/2019 chap06book

    35/41

    Looping Logic

    Adding integers from 1 to 10

    #!/bin/csh

    set i=1set sum=0while ($i

  • 7/28/2019 chap06book

    36/41

    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

  • 7/28/2019 chap06book

    37/41

    Switch Logic

    switch ( var )

    case string1:

    command_set_1

    breaksw

    case string2:

    command_set_2

    breaksw

    default

    command_set_3

    endsw

  • 7/28/2019 chap06book

    38/41

    Switch Logic

    #!/bin/cshif ($#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

  • 7/28/2019 chap06book

    39/41

    Chapter Summary

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

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

    editor, contain instructions that do not need to bewritten from scratch, but rather can be selectivelychosen from the operating systems inventory of

    executable commands

  • 7/28/2019 chap06book

    40/41

    Chapter Summary Section AContinued

    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, includingmany for performing arithmetic operations

    The logic structures supported by the shell aresequential, decision, looping, and case

  • 7/28/2019 chap06book

    41/41

    Homework 1

    Please refer to handout.