Advanced UNIX CIS 218 Advanced UNIX 6 . The Bourne and Bash Shells - - PowerPoint PPT Presentation

advanced unix
SMART_READER_LITE
LIVE PREVIEW

Advanced UNIX CIS 218 Advanced UNIX 6 . The Bourne and Bash Shells - - PowerPoint PPT Presentation

Advanced UNIX CIS 218 Advanced UNIX 6 . The Bourne and Bash Shells Objectives explain how to write Bourne and Bash Shell scripts 1 CIS 218 Advanced UNIX Overview 1 . Making a File Executable 2 . Combining Commands 3 . Redirecting Output


slide-1
SLIDE 1

CIS 218 Advanced UNIX 1

Advanced UNIX

 Objectives

– explain how to write Bourne and Bash Shell scripts

CIS 218 – Advanced UNIX

  • 6. The Bourne and

Bash Shells

slide-2
SLIDE 2

CIS 218 Advanced UNIX 2

Overview

1. Making a File Executable 2. Combining Commands 3. Redirecting Output 4. Executing Scripts 5. Variables 6. Control Flow

continued

slide-3
SLIDE 3

CIS 218 Advanced UNIX 3

7. Functions 8. Other Commands 9. Here Documents

  • 10. Debugging
  • 11. More Information
slide-4
SLIDE 4

CIS 218 Advanced UNIX 4

  • 1. Making a File Executable

 $ cat whoson

date echo Users currently logged on who  Wrong: $ whoson whoson: Permission denied

slide-5
SLIDE 5

CIS 218 Advanced UNIX 5

Right:

 $ ls -lg whoson

  • rw-r--r-- 1 ad pubs 42 Jun 17 10:55 whoson

$ chmod u+x whoson $ ls -lg whoson

  • rwxr--r-- 1 ad pubs 42 Jun 17 10:55 whoson

 $ whoson

Tue Nov 7 13:21:34 ICT 2000 Users currently logged in ad consol Nov 7 08:26 jenny tty02 Nov 7 10:04

slide-6
SLIDE 6

CIS 218 Advanced UNIX 6

Possible PATH Problem

 $ whoson

whoson: Command not found  Due to PATH shell variable (see later)  Quick fixes: $ ./whoson

  • r

$ sh whoson

slide-7
SLIDE 7

CIS 218 Advanced UNIX 7

  • 2. Combining Commands

 Sequencing:

$ a ; b ; c

 same as:

$ a $ b $ c

slide-8
SLIDE 8

CIS 218 Advanced UNIX 8

Process Creation (&)

 $ a & b & c

14271

(PID for a)

14272

(PID for b)

 $ a & b & c &

14290 14291 14292 $

 $ a | b | c &

14302

(PID for piped commands)

slide-9
SLIDE 9

CIS 218 Advanced UNIX 9

Processes in Action

$ cat a echo -n “aaaaaaaaaaaaaaaaaaaaa” echo -n “aaaaaaaaaaaaaaaaaaaaa” sleep 2 echo -n “aaaaaaaaaaaaaaaaaaaaa” echo -n “aaaaaaaaaaaaaaaaaaaaa”  Similarly for b and c  Try the following a few times: $ a & b & c & On calvin there isn't much variation unless the machine is loaded.

slide-10
SLIDE 10

CIS 218 Advanced UNIX 10

  • 3. Redirecting Output

 1>

redirect standard output (stdout) 2> redirect standard error (stderr)

$ cat a b 1> out 2> err cat a b

  • ut

err stdout stderr Files

slide-11
SLIDE 11

CIS 218 Advanced UNIX 11

>&

 redirect one stream into another:

– 2>&1 redirect stderr into stdout

$ cat a b 1> theLot 2>&1 cat a b theLot stderr stdout

slide-12
SLIDE 12

CIS 218 Advanced UNIX 12

  • 4. Executing Scripts

 Make sure that a script is executed by the

Bourne Shell:

$ sh whoson

(no need for chmod)

 or:

$ cat boss

#!/bin/sh echo Definitely Bourne Shell Script continued

slide-13
SLIDE 13

CIS 218 Advanced UNIX 13

 On Linux machines (e.g. calvin), the

Bourne shell has been replaced by Bash

– sh means the Bash shell

slide-14
SLIDE 14

CIS 218 Advanced UNIX 14

  • 5. Variables

5.1. User-defined Variables 5.2. Environment Variables 5.3. Readonly Shell Variables

slide-15
SLIDE 15

CIS 218 Advanced UNIX 15

5.1. User-defined Variables

 $ person=alex

$ echo person person $ echo $person alex

 $var returns the value stored in var

– called substitution

No spaces around the =

slide-16
SLIDE 16

CIS 218 Advanced UNIX 16

5.1.1. Switch off Substitution

 Swich off substitution with 'var' or \var

 $ echo '$person'

$person $ echo \$person $person

slide-17
SLIDE 17

CIS 218 Advanced UNIX 17

5.1.2. Switch off Special Chars (")

 "" switches off the special meaning of characters

used in filename generation (e.g. *, ?)

 $ ls

// directory contents ad.report ad.summary

 $ memo=ad*

$ echo "$memo" ad* $ echo $memo ad.report ad.summary * means only * * means any number

  • f characters
slide-18
SLIDE 18

CIS 218 Advanced UNIX 18

5.1.3. Exporting Variables

 Normally a variable is local to the running

script (the process).

 It is sometimes useful if running scripts

(processes) can access another script’s variables.

 e.g. extest subtest cheese=english calls we want to use cheese in subtest

slide-19
SLIDE 19

CIS 218 Advanced UNIX 19

No Exporting: extest1 & subtest

 $ cat extest1

cheese=english echo "extest1 1: $cheese" subtest echo "extest1 2: $cheese" $cat subtest echo "subtest 1: $cheese" cheese=swiss echo "subtest 2: $cheese" continued Using " is a good habit, see later

slide-20
SLIDE 20

CIS 218 Advanced UNIX 20

 $ extest1

extest1 1: english subtest 1: subtest 2: swiss extest1 2: english subtest does not see extest1's cheese value extest1 is not affected by subtest's setting of cheese

slide-21
SLIDE 21

CIS 218 Advanced UNIX 21

Exporting: extest2 & subtest

 $ cat extest2

export cheese cheese=english echo “extest2 1: $cheese” subtest echo “extest2 2: $cheese”

 $ extest2

extest2 1: english subtest 1: english subtest 2: swiss extest2 2: english cheese value passed in change not exported from subtest

slide-22
SLIDE 22

CIS 218 Advanced UNIX 22

5.1.4. Reading

 $ cat readln

echo -n “Type: ” read ln echo “You entered: $ln”

 $ readln

Type: The Wizard of Oz You entered: The Wizard of Oz read inputs everything up to the newline

slide-23
SLIDE 23

CIS 218 Advanced UNIX 23

No Quotes

 $ cat readlnnq

echo -n “Type: ” read ln echo You entered: $ln

 $ ls

ad.report summary1 $ readlnnq Type: * You entered: ad.report summary1 directory contents

slide-24
SLIDE 24

CIS 218 Advanced UNIX 24

5.1.5. Executing Commands

 $ cat proc_cmd

echo -n “Enter a command: ” read command $command echo Thanks

 $ proc_cmd

Enter a command: echo Display this Display this Thanks A very simple shell

slide-25
SLIDE 25

CIS 218 Advanced UNIX 25

5.1.6. Splitting Input

 $ cat split3

echo -n “Enter something: ” read word1 word2 word3 echo “Word 1 is: $word1” echo “Word 2 is: $word2” echo “Word 3 is: $word3”

 $ split3

Enter something: this is something Word1 is: this Word2 is: is Word3 is: something Text is split based on white space.

slide-26
SLIDE 26

CIS 218 Advanced UNIX 26

 $ split3

Enter something: this is something else, x Word1 is: this Word2 is: is Word3 is: something else, x The last variable gets everything that is left in the input.

slide-27
SLIDE 27

CIS 218 Advanced UNIX 27

5.1.7. Command Subsitution

 $ cat mydir

this_dir=‘pwd‘ echo “Using the $this_dir directory.” this_date=$(date) echo "Today's date: $this_date"

 $ mydir

Using /home/ad/teach/adv-unix/bourne directory Today's date: Tue Nov 7 13:52:46 ICT 2000 $ A Bash addition Must use ‘

slide-28
SLIDE 28

CIS 218 Advanced UNIX 28

5.2. Environment Variables

 Most environment variables get their

values from the shell at login.

 The values of some of the variables can be

set by editing the .profile file in your home directory

– Bash uses .bash_profile and .bashrc

slide-29
SLIDE 29

CIS 218 Advanced UNIX 29

5.2.1. Examples

 HOME

pathname of your home directory

 $ pwd

/home/ad/planning $ echo $HOME /home/ad $ cd $ pwd /home/ad continued cd uses HOME to return to your home directory

slide-30
SLIDE 30

CIS 218 Advanced UNIX 30

 PATH

– directories where executable can be found – represented as a string of pathnames separated by ‘:’s

 $ echo $PATH

/usr/local/bin:/usr/bin:/bin: $ PATH=SPATH":/home/ad/bin:." $ echo $PATH /usr/local/bin:/usr/bin:/bin:/home/ad/bin:. Extend the default PATH

slide-31
SLIDE 31

CIS 218 Advanced UNIX 31

Note for SysAdmins

 If you are the system administrator

(superuser, root) for your machine, do not extend your path with "."

– it opens you to potential attack by hackers – e.g. 'fake' UNIX utilities placed in the current directory

slide-32
SLIDE 32

CIS 218 Advanced UNIX 32

5.2.2. Typical .profile

 $ cat .profile

TERM=vt100 PATH=$PATH":/home/ad/bin:." PS1=“ad: “ CDPATH=:$HOME export TERM PATH PS1 CDPATH stty kill ^u

 $ . .profile

export needed in the Bourne shell

slide-33
SLIDE 33

CIS 218 Advanced UNIX 33

5.2.3. Typical .bash_profile

 On calvin, .bash_profile simply invokes

your .bashrc (if it exists):

umask 002 if [ -f ~/.bashrc -a PS1="\$ " ]; then . ~/.bashrc fi continued These shell commands will be explained later

slide-34
SLIDE 34

CIS 218 Advanced UNIX 34

Typical .bashrc

 PS1="\u@\h$ "

# PS1="\w[\#]$ " PATH=$PATH":." alias ls='/bin/ls -F' alias dir='ls -ba' alias cls="clear" : : psgrep() { ps aux | grep $1 | grep -v grep }

These features will be explained later. No export needed

slide-35
SLIDE 35

CIS 218 Advanced UNIX 35

5.2.4. set

 The current settings for the environment

variables can be listed with set:

$ set | more BASH=/bin/bash : PATH=/usr/local/bin:/usr/bin:/bin:. : PS1='\u@\h$ ' :

slide-36
SLIDE 36

CIS 218 Advanced UNIX 36

5.3. Readonly Shell Variables

 These are environment variables that

cannot have their values changed.

 Most of them relate to the arguments

supplied to a script when it is called.

slide-37
SLIDE 37

CIS 218 Advanced UNIX 37

5.3.1. Script Name ($0)

 $ cat abc

echo The name of this script is $0

 $ abc

The name of this script is abc

slide-38
SLIDE 38

CIS 218 Advanced UNIX 38

5.3.2. Script Arguments ($1, $2,..., $9)

 $ cat display_5args

echo The first five command line echo arguments are $1 $2 $3 $4 $5

 $ display_5args jenny alex helen

The first five command line arguments are jenny alex helen If the variable has no value, then nothing is printed.

slide-39
SLIDE 39

CIS 218 Advanced UNIX 39

5.3.3. All Arguments ($*)

 $ cat display_all

echo $*

 $ display_all a b c de fg hi jk mno pqr

stu w x y z a b c de fg hi jk mno pqr stu w x y z

 $@ is like $* but puts “...” around each

printed argument

slide-40
SLIDE 40

CIS 218 Advanced UNIX 40

5.3.4. Number of Arguments ($#)

 $ cat num_args

echo “This script has $# arguments.”

 num_args helen alex jenny

This script has 3 arguments

slide-41
SLIDE 41

CIS 218 Advanced UNIX 41

5.3.5. The shift Commnd

 shift moves argument values on the

command line one $<number> to the left.

 Overcomes limit of 9 argument variables

($1, $2, ..., $9)

continued

slide-42
SLIDE 42

CIS 218 Advanced UNIX 42

 $ cat demo_shift

echo “arg1= $1 arg2= $2 arg3= $3” shift echo “arg1= $1 arg2= $2 arg3= $3” shift echo “arg1= $1 arg2= $2 arg3= $3” shift

 $ demo_shift alice helen jenny june

arg1= alice arg2= helen arg3= jenny arg1= helen arg2= jenny arg3= june arg1= jenny arg2= june arg3= jenny "moves" to the left.

slide-43
SLIDE 43

CIS 218 Advanced UNIX 43

5.3.6. The set Command (Again)

 set ‘cmd‘

(must use ‘)

– evaluates cmd and assigns its values to the script command line arguments ($1, $2, ..., $9, $*) – the values in cmd output are separated by whitespace

continued

slide-44
SLIDE 44

CIS 218 Advanced UNIX 44

 $ date

Fri Jun 17 23:04:09 GMT+7 1996 $ cat dateset set ‘date‘ echo $* echo echo “Argument 1: $1” echo “Argument 2: $2” echo “Argument 3: $3” echo $2 $3, $6 continued The date values are assigned to $1, $2, etc.

slide-45
SLIDE 45

CIS 218 Advanced UNIX 45

 $ dataset

Fri Jun 17 23:04:13 GMT+7 1996 Argument 1: Fri Argument 2: Jun Argument 3: 17 Jun 17, 1996

slide-46
SLIDE 46

CIS 218 Advanced UNIX 46

  • 6. Command Flow

6.1. Branching 6.2. Test Forms 6.3. Looping 6.4. break, continue, : 6.5. trap

slide-47
SLIDE 47

CIS 218 Advanced UNIX 47

6.1. Branching

 $ cat same_word

echo -n “word 1: ” read word1 echo -n “word 2: ” read word2 if test "$word1" = "$word2" then echo Match fi echo End of Program Use " to stop filename expansion continued

slide-48
SLIDE 48

CIS 218 Advanced UNIX 48

 $ same_word

word1: peach word2: peach Match End of Program

slide-49
SLIDE 49

CIS 218 Advanced UNIX 49

 $ cat chkargs

if [ $# = 0 ] then echo Usage: chkargs argument... 1>&2 exit 1 fi echo Program running exit 0

 $ chkargs

Usage: chkargs argument... $ chkargs abc Program running Redirect stdout to stderr

6.1.1. Second Format

slide-50
SLIDE 50

CIS 218 Advanced UNIX 50

6.1.2. if-then-else

 $ cat show

if [ $# = 0 ]; then echo Usage: show [-v] filenames 1>&2 exit 1 fi if [ “$1” != “-v” ] then cat “$@” else shift more “$@” fi C programmers prefer this format Use: $ show -v f1.txt f2.txt

slide-51
SLIDE 51

CIS 218 Advanced UNIX 51

6.1.3. if-then-elif

 $ cat same3

echo -n “word 1: ” read word1 echo -n “word 2: ” read word2 echo -n “word 3: ” read word3 if [ “$word1” = “$word2” -a \ “$word2” = “$word3” ] then echo “Match: words 1, 2, and 3” continued For multiway branches

  • a means "and"

\ means "continued

  • n next line"
slide-52
SLIDE 52

CIS 218 Advanced UNIX 52

elif [ “$word1” = “$word2” ] then echo “Match: words 1 and 2” elif [ “$word1” = “$word3” ] then echo “Match: words 1 and 3” elif [ “$word2” = “$word3” ] then echo “Match: words 2 and 3” else echo “No match” fi

slide-53
SLIDE 53

CIS 218 Advanced UNIX 53

6.1.4. case

 $cat command_menu

#!/bin/sh # menu interface to simple commands echo “\n COMMAND MENU\n” echo “ a. Current date and time” echo “ b. Users currently logged in” echo “ c. Name of working directory” echo “ d. Contents of working directory” echo -n “Enter a, b, c, or d: ” read answer echo continued Better style: specify the shell, and comment the code.

slide-54
SLIDE 54

CIS 218 Advanced UNIX 54

case “$answer” in a) date ;; b) who ;; c) pwd ;; d) ls -C ;; *) echo “$answer not legal” ;; esac echo * is the default; always include it at the end

slide-55
SLIDE 55

CIS 218 Advanced UNIX 55

 $ command_menu

COMMAND MENU

  • a. Current date and time
  • b. Users currently logged in
  • c. Name of working directory
  • d. Contents of working directory

Enter a, b, c, or d: a Fri Jun 17 14:11:57 GMT 1996

slide-56
SLIDE 56

CIS 218 Advanced UNIX 56

Other case Patterns

 ?

matches a single character

 [...]

any character in the brackets. Use - to specify a range (e.g. a-z)

 |

  • r (e.g. a|A)

 *

it can be used to match "any number of characters"

slide-57
SLIDE 57

CIS 218 Advanced UNIX 57

 $cat timeDay

#!/bin/sh echo Is it morning? Answer yes or no read timeofday case "$timeofday" in "yes" | "y" | "Yes" | "YES" ) echo "Good Morning" ;; [nN]* ) echo "Good Afternoon" ;; *) echo "Uhh??" ;; esac

slide-58
SLIDE 58

CIS 218 Advanced UNIX 58

6.2. test Forms

 Format: test expr [ expr ]  e.g. test “$word1” = “$word2” [ “$1” != “-v” ] [ “$word2” = “$word3” ] [ “$word1” = “$word2” -a \ “$word2” = “$word3” ] Used in the conditions of if's and loops.

slide-59
SLIDE 59

CIS 218 Advanced UNIX 59

6.2.1. String Expressions

 string1 = string2  string1 != string2  -n string

(true if string is not ““)

 -z string

(true if string is ““)

slide-60
SLIDE 60

CIS 218 Advanced UNIX 60

6.2.2. Numerical Expressions

 number1 -eq number2

(equality)

 number1 -ne number2

(inequality)

 number1 -lt number2

(<)

 number1 -le number2

(<=)

 number1 -gt number2

(>)

 number1 -ge number2

(>=)

slide-61
SLIDE 61

CIS 218 Advanced UNIX 61

6.2.4. File Test Expressions

 -f file

(file exists)

 -d file

(file exists but is a directory)

 -r file

(file is readable)

 -w file

(file is writable)

 -x file

(file is executable)

slide-62
SLIDE 62

CIS 218 Advanced UNIX 62

6.2.5. Combining Expressions

 ! expr

(not expr)

 expr1 -a expr2

(and)

– Bash allows && as well

 expr1 -o expr2

(or)

– Bash allows || as well

 ( expr )

slide-63
SLIDE 63

CIS 218 Advanced UNIX 63

6.3. Looping (for-in)

 Format: for loop-index in argument-list do commands done

slide-64
SLIDE 64

CIS 218 Advanced UNIX 64

 $ cat fruit

for fruit in apples oranges pears do echo $fruit done echo Task completed

 $ fruit

apples

  • ranges

pears Task completed

slide-65
SLIDE 65

CIS 218 Advanced UNIX 65

Looking for “for” in files

 First version of script: $ car file-fors1 for f in ‘ls‘ do echo $f done

slide-66
SLIDE 66

CIS 218 Advanced UNIX 66

 $ cat file-fors2

for f in ‘ls‘ do grep -i “for” $f > /dev/null if [ $? == 0 ] then echo $f fi done Ignore output

slide-67
SLIDE 67

CIS 218 Advanced UNIX 67

6.3.1. for

 $ cat whos

# Give user details from /etc/passwd if [ $# = 0 ] then echo Usage: whos id... 1>&2 exit 1 fi for i # read as for i in “$@” do awk -F: ’{print $1, $5}’ /etc/passwd | grep -i “$i” done awk variables with ’

slide-68
SLIDE 68

CIS 218 Advanced UNIX 68

6.3.2. while

 $ cat count

number=0 while [ $number -lt 10 ] do echo -n "$number" number=‘expr $number + 1‘ done echo

 $ count

0123456789 $

slide-69
SLIDE 69

CIS 218 Advanced UNIX 69

Watching for Mary to log in

 while sleep 60

do who | grep mary done  Disadvantages:

– if Mary is already logged in, then we must wait 60 secs to find out – we keep being told that Mary is logged in

slide-70
SLIDE 70

CIS 218 Advanced UNIX 70

6.3.3. until

 Format:

until command

do loop body until the command evaluates to true done  Watching (v.2): until who | grep mary do sleep 60 done loop until grep returns ‘true’ (0)

slide-71
SLIDE 71

CIS 218 Advanced UNIX 71

6.3.4. Extending Watching

 Generalise so can watch for anyone:

$ watchfor ad

 Watch for everyone logging in/out: $ watchwho

slide-72
SLIDE 72

CIS 218 Advanced UNIX 72

watchfor

#!/bin/sh # watchfor # watch for person supplied as argument if [ $# = 0 ] then echo “Usage: watchfor person” exit 1 fi until who | grep “$1” do sleep 60 done

slide-73
SLIDE 73

CIS 218 Advanced UNIX 73

watchwho

 Once a minute, run who and compare its

  • utput to that from a minute ago. Report

any differences.

 Keep the who output in files in /tmp  Give the files unique names by adding the

shell variable $$.

– $$ is the PID of the user’s shell

slide-74
SLIDE 74

CIS 218 Advanced UNIX 74

#!/bin/sh # watchwho: watch who logs in and out new=/tmp/wwho1.$$

  • ld=/tmp/wwho2.$$

> $old # create an empty file while true do who > $new diff $old $new mv $new $old sleep 60 done | awk ’/>/ {$1 = “in: “; print} /</ {$1 = “out: “; print}’

An advanced Shell programming technique: |

slide-75
SLIDE 75

CIS 218 Advanced UNIX 75

Use

 $ watchwho

in: root tty1 Nov 6 09:32 in: ad pts/3 Nov 8 08:49 (myrrh.coe.psu.ac.th) in: s4010441 pts/5 Nov 8 10:11 (192.168.0.134) in: ad pts/4 Nov 8 10:12 (myrrh.coe.psu.ac.th) in: s4010143 pts/17 Nov 7 23:57 (192.168.0.204)

  • ut: ad pts/4 Nov 8 10:12 (myrrh.coe.psu.ac.th)

in: ad pts/4 Nov 8 10:16 (myrrh.coe.psu.ac.th)

  • ut: ad pts/4 Nov 8 10:18 (myrrh.coe.psu.ac.th)

:

initial users

slide-76
SLIDE 76

CIS 218 Advanced UNIX 76

Notes

 diff uses ‘<‘ and ‘>‘ to distinguish data

from $old and $new

 $ diff old new

< ad > mary john ad

  • ld

john mary new continued

slide-77
SLIDE 77

CIS 218 Advanced UNIX 77

 The output from the while loop is piped

into awk

– only one call to awk is required – the "pipe" programming style

 A calvin problem: – awk had to be called with the -W interactive

  • ption so that its output was not buffered

– otherwise nothing would appear

while loop awk

slide-78
SLIDE 78

CIS 218 Advanced UNIX 78

6.3.5. Checking mail

 Have a script watch your mailbox

periodically, and report whenever the mailbox changes by printing “You have

mail”.  Usage: – $ checkmail # checks every 60 secs – $ checkmail 120 # checks every 120 secs

slide-79
SLIDE 79

CIS 218 Advanced UNIX 79

checkmail

#!/bin/sh # checkmail: watch mailbox for growth time=${1-60}

  • ldls="‘ls -l $MAIL‘"

while true do newls="‘ls -l $MAIL‘" echo $oldls $newls

  • ldls="$newls"

sleep $time done | awk ’$5 < $14 {print “You have mail”}’

uses the pipe technique

slide-80
SLIDE 80

CIS 218 Advanced UNIX 80

Notes

 $MAIL is a builtin shell variable, with the

value /var/spool/mail/$USER

 t=${1-60} sets t to $1 or, if no argument is

provided, to 60

– General form: ${var-thing} returns value of var if defined; otherwise

thing continued

slide-81
SLIDE 81

CIS 218 Advanced UNIX 81

 Use awk to print a message only when the

mailbox gets bigger:

– awk $5 $14 compares the size fields of the two ls -l calls output at the end of each iteration e.g. $ ls -l foo

  • rw-r--r-- 1 ad ad 34512 Nov 13 1996 foo

$ ls -l foo

  • rw-r--r-- 1 ad ad 34512 Nov 13 1996 foo

5th value 14th value

slide-82
SLIDE 82

CIS 218 Advanced UNIX 82

6.4. break, continue, :

 break and continue are used as in C:

– break escapes from a loop

for file in fred* do if [ -d "$file" ]; then # deleted? break # finish loop fi # do something # done

continued

slide-83
SLIDE 83

CIS 218 Advanced UNIX 83

 continue goes to the top of a loop:

for file in fred* do if [ -d "$file" ]; then # deleted? continue # go back to loop top fi # do something # done

continued

slide-84
SLIDE 84

CIS 218 Advanced UNIX 84

 The ':' command is the same as true, but

runs a tiny bit faster

– often used to simplify control logic

if [ -f fred ]; then # is fred a file? : # do nothing else # do something # fi

slide-85
SLIDE 85

CIS 218 Advanced UNIX 85

6.5. trap

 Capture user interrupts or system call failures.  Format (with ’): trap ’commands’ signal-numbers-or-name  Some signal numbers (names):

– 2 (INT) press delete or control-C – 3 (QUIT) press control-| or control-\ – 15 (TERM) kill command signal

continued

slide-86
SLIDE 86

CIS 218 Advanced UNIX 86

 A complete list of available signals is

given by typing trap -l at the command line.

 To ignore a signal, set the trap command

to be empty (’’)

 To reset signal processing, set the

command to -

continued

slide-87
SLIDE 87

CIS 218 Advanced UNIX 87

 $ cat inter

trap ’echo PROGRAM INTERRUPTED; exit 1’ INT while true do echo Program running. sleep 2 done

slide-88
SLIDE 88

CIS 218 Advanced UNIX 88

  • 7. Functions

 Bash allows shell scripts to use functions: function_name() { statements }  Functions must be defined textually before

they are used.

continued

slide-89
SLIDE 89

CIS 218 Advanced UNIX 89

 Functions can return integer values  Function parameters are passed by

modifying $*, $@, $#, $1 -- $9 while the function is executing.

 Local variables are defined with the local

keyword

– the other variables in a script are global by default

slide-90
SLIDE 90

CIS 218 Advanced UNIX 90

my_name

 #!/bin/sh

yes_or_no() { # a function echo "Is your name $* ?" while true do echo -n "Enter yes or no: " read x case "$x" in y | yes ) return 0;; n | no ) return 1;; * ) echo "Answer yes or no" esac done } # end of yes_or_no()

continued

slide-91
SLIDE 91

CIS 218 Advanced UNIX 91

# the main part of the script echo "Original parameters are $*" if yes_or_no "$1" then echo "Hi $1, nice name" else echo "Never mind" fi exit 0

slide-92
SLIDE 92

CIS 218 Advanced UNIX 92

Use

 $ my_name andrew davison

Original parameters are andrew davison Is your name andrew ? Enter yes or no: y Hi andrew, nice name $

slide-93
SLIDE 93

CIS 218 Advanced UNIX 93

  • 8. Useful Scripting Commands

 expr evaluates its argument as an

expression:

ans=‘expr $x + 1‘  The usually operators are available:

– + - * / (integer divison) % (modulo) – > >= < <= – = (equality) != – | (or) & (and)

continued

slide-94
SLIDE 94

CIS 218 Advanced UNIX 94

 Bash supports printf, as a more flexible echo – printf "format string" parameter1 ...  Very similar to printf() in C

– main restriction is no support for floats – only integers are supported in the shell

 $ printf "%s %d\t%s\n" "hi there" 15 students

hi there 15 students $

printf

slide-95
SLIDE 95

CIS 218 Advanced UNIX 95

  • 9. Here Documents

 A here document allows input to be passed

into a command from within a script

– the command thinks the input is coming from a file or input stream

 A here document begins with <<LABEL, and

ends with LABEL

– LABEL can be anything

slide-96
SLIDE 96

CIS 218 Advanced UNIX 96

 $ cat here1

#!/bin/sh cat <<!FUNKY! hello this is a here document !FUNKY!

 $ here1

hello this is a here document $

the here document

slide-97
SLIDE 97

CIS 218 Advanced UNIX 97

  • 10. Debugging

 Various options can be set when invoking a

shell script to help with debugging.

 There are two ways to set the options:

– from the command line when calling the script – from within the script by using set

continued

slide-98
SLIDE 98

CIS 218 Advanced UNIX 98

Command Line Set

 sh -n script

set -n

– do not execute the script, only parse it

 sh -v script

set -v

– echoes commands after executing them

 sh -x script

set -u

– warns when an undefined variable is used

slide-99
SLIDE 99

CIS 218 Advanced UNIX 99

  • 11. More Information

 The Bourne Shell:

– Ch. 10, Sobell

 Bourne/Bash:

– Beginning Linux Programming Neil Matthew and Rick Stones Chapter 2