Что такое findslide.org?

FindSlide.org - это сайт презентаций, докладов, шаблонов в формате PowerPoint.


Для правообладателей

Обратная связь

Email: Нажмите что бы посмотреть 

Яндекс.Метрика

Презентация на тему Bash programming. CSCI 330 the unix system

Содержание

BASIC SHELL PROGRAMMINGA script is a file that contains shell commandsdata structure: variablescontrol structure: sequence, decision, loopShebang line for bash shell script: #! /bin/bash #! /bin/shto run:make executable: % chmod +x scriptinvoke via: % ./scriptCSCI 330 -
CSCI 330 THE UNIX SYSTEMBash Programming BASIC SHELL PROGRAMMINGA script is a file that contains shell commandsdata structure: BASH SHELL PROGRAMMINGInputprompting usercommand line argumentsDecision:if-then-elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps CSCI 330 - The Unix System USER INPUTshell allows to prompt for user inputSyntax:read varname [more vars]orread –p USER INPUT EXAMPLE#! /bin/shread -p SPECIAL SHELL VARIABLESCSCI 330 - The Unix System EXAMPLES: COMMAND LINE ARGUMENTS% set tim bill ann fred   $1 BASH CONTROL STRUCTURESif-then-elsecaseloopsforwhileuntilselectCSCI 330 - The Unix System IF STATEMENTif commandthen	statementsfistatements are executed only if command succeeds, i.e. has return TEST COMMANDSyntax: 	test expression	[ expression ]evaluates ‘expression’ and returns true or falseExample:	if THE SIMPLE IF STATEMENTif [ condition ]; then	statementsfiexecutes the statements only if THE IF-THEN-ELSE STATEMENTif [ condition ]; then		statements-1else statements-2fiexecutes statements-1 if condition is THE IF…STATEMENTif [ condition ]; then	 statementselif [ condition ]; then RELATIONAL OPERATORSCSCI 330 - The Unix System COMPOUND LOGICAL EXPRESSIONS!			not&&		and||		orCSCI 330 - The Unix Systemand, or must be enclosed EXAMPLE: USING THE ! OPERATOR#!/bin/bashread -p EXAMPLE: USING THE && OPERATOR #!/bin/bashBonus=500read -p EXAMPLE: USING THE || OPERATOR#!/bin/bashread -p FILE TESTING 				Meaning-d file			True if ‘file’ is a directory-f file			True if ‘file’ EXAMPLE: FILE TESTING#!/bin/bashecho EXAMPLE: FILE TESTING#! /bin/bashif [ $# -lt 1 ]; then EXAMPLE: IF… STATEMENT# The following THREE if-conditions produce the same result* DOUBLE EXAMPLE: IF..ELIF... STATEMENT#!/bin/bashread -p THE CASE STATEMENTuse the case statement for a decision that is based CASE PATTERNchecked against word for matchmay also contain:	*	?	[ … ]	[:class:]multiple patterns can EXAMPLE 1: THE CASE STATEMENT#!/bin/bashecho EXAMPLE 2: THE CASE STATEMENT#!/bin/bashChildRate=3AdultRate=10SeniorRate=7read -p BASH PROGRAMMING: SO FARData structureVariablesNumeric variablesArraysUser inputControl structuresif-then-elsecaseCSCI 330 - The Unix System BASH PROGRAMMING: STILL TO COMEControl structuresRepetitiondo-while, repeat-untilforselectFunctionsTrapping signalsCSCI 330 - The Unix System REPETITION CONSTRUCTSCSCI 330 - The Unix System THE WHILE LOOPPurpose:	To execute commands in “command-list” as long as “expression” evaluates EXAMPLE: USING THE WHILE LOOP#!/bin/bash COUNTER=0 while [ $COUNTER -lt 10 ] EXAMPLE: USING THE WHILE LOOP#!/bin/bashCont= EXAMPLE: USING THE WHILE LOOP#!/bin/bash # copies files from home- into the THE UNTIL LOOPPurpose:	To execute commands in “command-list” as long as “expression” evaluates EXAMPLE: USING THE UNTIL LOOP#!/bin/bash COUNTER=20 until [ $COUNTER -lt 10 ] EXAMPLE: USING THE UNTIL LOOP#!/bin/bashStop= THE FOR LOOPPurpose: 	To execute commands as many times as the number EXAMPLE 1: THE FOR LOOP#!/bin/bashfor i in 7 9 2 3 4 EXAMPLE 2: USING THE FOR LOOP#!/bin/bash# compute the average weekly temperaturefor num LOOPING OVER ARGUMENTSsimplest form will iterate over all command line arguments:	#! /bin/bash	for SELECT COMMANDConstructs simple menu from word listAllows user to enter a number SELECT EXAMPLE#! /bin/bashselect var in alpha beta gammado   echo $vardonePrints:CSCI SELECT DETAILPS3 is select sub-prompt$REPLY is user input (the number)#! /bin/bashPS3= SELECT EXAMPLE#!/bin/bashecho BREAK AND CONTINUEInterrupt for, while or until loopThe break statement transfer THE BREAK COMMANDwhile [ condition ]do  cmd-1  break  cmd-ndoneecho THE CONTINUE COMMANDwhile [ condition ]do  cmd-1  continue  cmd-ndoneecho EXAMPLE:for index in 1 2 3 4 5 6 7 8 9 DONE !BASH SHELL PROGRAMMINGSequenceDecision:if-then-elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps CSCI 330 - The Unix System still to come SHELL FUNCTIONSA shell function is similar to a shell scriptstores a series SHELL FUNCTIONSmust be defined before they can be referencedusually placed at the EXAMPLE: FUNCTION#!/bin/bash funky () { 	# This is a simple function 	echo EXAMPLE: FUNCTION#!/bin/bashfun () { # A somewhat more complex function. 	JUST_A_SECOND=1 	let FUNCTION PARAMETERSNeed not be declaredArguments provided via function call are accessible inside EXAMPLE: FUNCTION WITH PARAMETER#! /bin/shtestfile() { if [ $# -gt 0 ]; EXAMPLE: FUNCTION WITH PARAMETERS#! /bin/bashcheckfile() {  for file  do LOCAL VARIABLES IN FUNCTIONSVariables defined within functions are global,	i.e. their values are EXAMPLE: FUNCTION#! /bin/bashglobal= HANDLING SIGNALSUnix allows you to send a signal to any process-1 = SIGNALS ON LINUX% kill -l 1) SIGHUP    2) SIGINT HANDLING SIGNALSDefault action for most signals is to end processterm: signal handlerBash EXAMPLE: TRAP HANGUP#! /bin/bash# kill -1 won’t kill this process# kill -2 EXAMPLE: TRAP MULTIPLE SIGNALS#! /bin/sh# plain kill or kill -9 will kill EXAMPLE: REMOVING TEMP FILES#! /bin/bashtrap 'cleanup; exit' 2cleanup () { RESTORING DEFAULT HANDLERStrap without a command list will remove a signal handlerUse DEBUG SHELL PROGRAMSDebugging is troubleshooting errors that may occur during the execution DEBUGGING USING “SET”The “set” command is a shell built-in commandhas options to DONE !SUMMARY: BASH SHELL PROGRAMMINGSequenceDecision:if-then-elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps CSCI 330 - The Unix System
Слайды презентации

Слайд 2 BASIC SHELL PROGRAMMING
A script is a file that

BASIC SHELL PROGRAMMINGA script is a file that contains shell commandsdata

contains shell commands
data structure: variables
control structure: sequence, decision, loop
Shebang

line for bash shell script:
#! /bin/bash
#! /bin/sh
to run:
make executable: % chmod +x script
invoke via: % ./script

CSCI 330 - The Unix System


Слайд 3 BASH SHELL PROGRAMMING
Input
prompting user
command line arguments
Decision:
if-then-else
case
Repetition
do-while, repeat-until
for
select
Functions
Traps
CSCI

BASH SHELL PROGRAMMINGInputprompting usercommand line argumentsDecision:if-then-elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps CSCI 330 - The Unix System

330 - The Unix System


Слайд 4 USER INPUT
shell allows to prompt for user input
Syntax:

read

USER INPUTshell allows to prompt for user inputSyntax:read varname [more vars]orread

varname [more vars]

or

read –p "prompt" varname [more vars]

words entered

by user are assigned to
varname and “more vars”
last variable gets rest of input line

CSCI 330 - The Unix System


Слайд 5 USER INPUT EXAMPLE
#! /bin/sh
read -p "enter your name:

USER INPUT EXAMPLE#! /bin/shread -p

" first last

echo "First name: $first"
echo "Last name: $last"

CSCI

330 - The Unix System

Слайд 6 SPECIAL SHELL VARIABLES
CSCI 330 - The Unix System

SPECIAL SHELL VARIABLESCSCI 330 - The Unix System

Слайд 7 EXAMPLES: COMMAND LINE ARGUMENTS
% set tim bill ann

EXAMPLES: COMMAND LINE ARGUMENTS% set tim bill ann fred  $1

fred
$1 $2 $3 $4
% echo

$*
tim bill ann fred
% echo $#
4
% echo $1
tim
% echo $3 $4
ann fred

CSCI 330 - The Unix System

The ‘set’ command can be used to assign values to positional parameters


Слайд 8 BASH CONTROL STRUCTURES
if-then-else
case
loops
for
while
until
select
CSCI 330 - The Unix System

BASH CONTROL STRUCTURESif-then-elsecaseloopsforwhileuntilselectCSCI 330 - The Unix System

Слайд 9 IF STATEMENT
if command
then
statements
fi


statements are executed only if command

IF STATEMENTif commandthen	statementsfistatements are executed only if command succeeds, i.e. has

succeeds, i.e. has return status “0”
CSCI 330 - The

Unix System

Слайд 10 TEST COMMAND
Syntax:
test expression
[ expression ]
evaluates ‘expression’ and

TEST COMMANDSyntax: 	test expression	[ expression ]evaluates ‘expression’ and returns true or

returns true or false

Example:
if test –w "$1"
then
echo

"file $1 is write-able"
fi

CSCI 330 - The Unix System


Слайд 11 THE SIMPLE IF STATEMENT
if [ condition ]; then
statements
fi

executes

THE SIMPLE IF STATEMENTif [ condition ]; then	statementsfiexecutes the statements only

the statements only if condition is true
CSCI 330 -

The Unix System

Слайд 12 THE IF-THEN-ELSE STATEMENT
if [ condition ]; then
statements-1
else
statements-2
fi

executes

THE IF-THEN-ELSE STATEMENTif [ condition ]; then		statements-1else statements-2fiexecutes statements-1 if condition

statements-1 if condition is true
executes statements-2 if condition is

false


CSCI 330 - The Unix System


Слайд 13 THE IF…STATEMENT
if [ condition ]; then
statements
elif [

THE IF…STATEMENTif [ condition ]; then	 statementselif [ condition ]; then

condition ]; then
statement
else
statements
fi

The

word elif stands for “else if”
It is part of the if statement and cannot be used by itself

CSCI 330 - The Unix System


Слайд 14 RELATIONAL OPERATORS
CSCI 330 - The Unix System

RELATIONAL OPERATORSCSCI 330 - The Unix System

Слайд 15 COMPOUND LOGICAL EXPRESSIONS
! not


&& and
|| or
CSCI 330 - The Unix System
and,

COMPOUND LOGICAL EXPRESSIONS!			not&&		and||		orCSCI 330 - The Unix Systemand, or must be

or
must be enclosed within

[[

]]



Слайд 16 EXAMPLE: USING THE ! OPERATOR
#!/bin/bash

read -p "Enter years

EXAMPLE: USING THE ! OPERATOR#!/bin/bashread -p

of work: " Years
if [ ! "$Years" -lt 20

]; then
echo "You can retire now."
else
echo "You need 20+ years to retire"
fi

CSCI 330 - The Unix System


Слайд 17 EXAMPLE: USING THE && OPERATOR
#!/bin/bash

Bonus=500
read -p "Enter

EXAMPLE: USING THE && OPERATOR #!/bin/bashBonus=500read -p

Status: " Status
read -p "Enter Shift: " Shift
if [[

"$Status" = "H" && "$Shift" = 3 ]]
then
echo "shift $Shift gets \$$Bonus bonus"
else
echo "only hourly workers in"
echo "shift 3 get a bonus"
fi

CSCI 330 - The Unix System


Слайд 18 EXAMPLE: USING THE || OPERATOR
#!/bin/bash

read -p "Enter calls

EXAMPLE: USING THE || OPERATOR#!/bin/bashread -p

handled:" CHandle
read -p "Enter calls closed: " CClose
if [[

"$CHandle" -gt 150 || "$CClose" -gt 50 ]]
then
echo "You are entitled to a bonus"
else
echo "You get a bonus if the calls"
echo "handled exceeds 150 or"
echo "calls closed exceeds 50"
fi

CSCI 330 - The Unix System


Слайд 19 FILE TESTING
Meaning
-d file True if ‘file’ is a

FILE TESTING 				Meaning-d file			True if ‘file’ is a directory-f file			True if

directory
-f file True if ‘file’ is an ord. file
-r file True

if ‘file’ is readable
-w file True if ‘file’ is writable
-x file True if ‘file’ is executable
-s file True if length of ‘file’ is nonzero

CSCI 330 - The Unix System


Слайд 20 EXAMPLE: FILE TESTING
#!/bin/bash
echo "Enter a filename: "
read filename
if

EXAMPLE: FILE TESTING#!/bin/bashecho

[ ! –r "$filename" ]
then
echo "File

is not read-able"
exit 1
fi

CSCI 330 - The Unix System


Слайд 21 EXAMPLE: FILE TESTING
#! /bin/bash

if [ $# -lt 1

EXAMPLE: FILE TESTING#! /bin/bashif [ $# -lt 1 ]; then

]; then
echo "Usage: filetest filename"

exit 1
fi
if [[ ! -f "$1" || ! -r "$1" || ! -w "$1" ]]
then
echo "File $1 is not accessible"
exit 1
fi

CSCI 330 - The Unix System


Слайд 22 EXAMPLE: IF… STATEMENT
# The following THREE if-conditions produce

EXAMPLE: IF… STATEMENT# The following THREE if-conditions produce the same result*

the same result

* DOUBLE SQUARE BRACKETS
read -p "Do you

want to continue?" reply
if [[ $reply = "y" ]]; then
echo "You entered " $reply
fi

* SINGLE SQUARE BRACKETS
read -p "Do you want to continue?" reply
if [ $reply = "y" ]; then
echo "You entered " $reply
fi

* "TEST" COMMAND
read -p "Do you want to continue?" reply
if test $reply = "y"; then
echo "You entered " $reply
fi

CSCI 330 - The Unix System


Слайд 23 EXAMPLE: IF..ELIF... STATEMENT
#!/bin/bash

read -p "Enter Income Amount: "

EXAMPLE: IF..ELIF... STATEMENT#!/bin/bashread -p

Income
read -p "Enter Expenses Amount: " Expense

let Net=$Income-$Expense

if [

"$Net" -eq "0" ]; then
echo "Income and Expenses are equal - breakeven."
elif [ "$Net" -gt "0" ]; then
echo "Profit of: " $Net
else
echo "Loss of: " $Net
fi

CSCI 330 - The Unix System


Слайд 24 THE CASE STATEMENT
use the case statement for a

THE CASE STATEMENTuse the case statement for a decision that is

decision that is based on multiple choices
Syntax:
case word in
pattern1)

command-list1
;;
pattern2) command-list2
;;
patternN) command-listN
;;
esac

CSCI 330 - The Unix System


Слайд 25 CASE PATTERN
checked against word for match
may also contain:
*
?
[

CASE PATTERNchecked against word for matchmay also contain:	*	?	[ … ]	[:class:]multiple patterns

… ]
[:class:]
multiple patterns can be listed via:
|
CSCI 330 -

The Unix System

Слайд 26 EXAMPLE 1: THE CASE STATEMENT
#!/bin/bash
echo "Enter Y to

see all files including hidden files"
echo "Enter N to

see all non-hidden files"
echo "Enter q to quit"

read -p "Enter your choice: " reply

case $reply in
Y|YES) echo "Displaying all (really…) files"
ls -a ;;
N|NO) echo "Display all non-hidden files..."
ls ;;
Q) exit 0 ;;

*) echo "Invalid choice!"; exit 1 ;;
esac

CSCI 330 - The Unix System


Слайд 27 EXAMPLE 2: THE CASE STATEMENT
#!/bin/bash
ChildRate=3
AdultRate=10
SeniorRate=7
read -p "Enter your

EXAMPLE 2: THE CASE STATEMENT#!/bin/bashChildRate=3AdultRate=10SeniorRate=7read -p

age: " age
case $age in
[1-9]|[1][0-2]) # child,

if age 12 and younger
echo "your rate is" '$'"$ChildRate.00" ;;
# adult, if age is between 13 and 59 inclusive
[1][3-9]|[2-5][0-9])
echo "your rate is" '$'"$AdultRate.00" ;;
[6-9][0-9]) # senior, if age is 60+
echo "your rate is" '$'"$SeniorRate.00" ;;
esac

CSCI 330 - The Unix System


Слайд 28 BASH PROGRAMMING: SO FAR
Data structure
Variables
Numeric variables
Arrays
User input
Control structures
if-then-else
case
CSCI

BASH PROGRAMMING: SO FARData structureVariablesNumeric variablesArraysUser inputControl structuresif-then-elsecaseCSCI 330 - The Unix System

330 - The Unix System


Слайд 29 BASH PROGRAMMING: STILL TO COME

Control structures
Repetition
do-while, repeat-until
for
select
Functions
Trapping signals
CSCI

BASH PROGRAMMING: STILL TO COMEControl structuresRepetitiondo-while, repeat-untilforselectFunctionsTrapping signalsCSCI 330 - The Unix System

330 - The Unix System


Слайд 30 REPETITION CONSTRUCTS
CSCI 330 - The Unix System

REPETITION CONSTRUCTSCSCI 330 - The Unix System

Слайд 31 THE WHILE LOOP
Purpose:
To execute commands in “command-list” as

THE WHILE LOOPPurpose:	To execute commands in “command-list” as long as “expression”

long as “expression” evaluates to true

Syntax:
while [ expression ]
do
command-list
done
CSCI

330 - The Unix System

Слайд 32 EXAMPLE: USING THE WHILE LOOP
#!/bin/bash
COUNTER=0
while [

EXAMPLE: USING THE WHILE LOOP#!/bin/bash COUNTER=0 while [ $COUNTER -lt 10

$COUNTER -lt 10 ]
do
echo The

counter is $COUNTER
let COUNTER=$COUNTER+1
done

CSCI 330 - The Unix System


Слайд 33 EXAMPLE: USING THE WHILE LOOP
#!/bin/bash

Cont="Y"
while [ $Cont =

EXAMPLE: USING THE WHILE LOOP#!/bin/bashCont=

"Y" ]; do
ps -A
read -p "want to

continue? (Y/N)" reply
Cont=`echo $reply | tr [:lower:] [:upper:]`
done
echo "done"

CSCI 330 - The Unix System


Слайд 34 EXAMPLE: USING THE WHILE LOOP
#!/bin/bash
# copies files

EXAMPLE: USING THE WHILE LOOP#!/bin/bash # copies files from home- into

from home- into the webserver- directory
# A new

directory is created every hour

PICSDIR=/home/carol/pics
WEBDIR=/var/www/carol/webcam
while true; do
DATE=`date +%Y%m%d`
HOUR=`date +%H`
mkdir $WEBDIR/"$DATE"
while [ $HOUR -ne "00" ]; do
DESTDIR=$WEBDIR/"$DATE"/"$HOUR"
mkdir "$DESTDIR"
mv $PICSDIR/*.jpg "$DESTDIR"/
sleep 3600
HOUR=`date +%H`
done
done


CSCI 330 - The Unix System


Слайд 35 THE UNTIL LOOP
Purpose:
To execute commands in “command-list” as

THE UNTIL LOOPPurpose:	To execute commands in “command-list” as long as “expression”

long as “expression” evaluates to false

Syntax:
until [ expression ]
do
command-list
done
CSCI

330 - The Unix System

Слайд 36 EXAMPLE: USING THE UNTIL LOOP
#!/bin/bash

COUNTER=20
until [

EXAMPLE: USING THE UNTIL LOOP#!/bin/bash COUNTER=20 until [ $COUNTER -lt 10

$COUNTER -lt 10 ]
do
echo $COUNTER


let COUNTER-=1
done

CSCI 330 - The Unix System


Слайд 37 EXAMPLE: USING THE UNTIL LOOP
#!/bin/bash

Stop="N"
until [ $Stop =

EXAMPLE: USING THE UNTIL LOOP#!/bin/bashStop=

"Y" ]; do
ps -A
read -p "want to

stop? (Y/N)" reply
Stop=`echo $reply | tr [:lower:] [:upper:]`
done
echo "done"

CSCI 330 - The Unix System


Слайд 38 THE FOR LOOP
Purpose:
To execute commands as many

THE FOR LOOPPurpose: 	To execute commands as many times as the

times as the number of words in the “argument-list”

Syntax:
for

variable in argument-list
do
commands
done

CSCI 330 - The Unix System


Слайд 39 EXAMPLE 1: THE FOR LOOP
#!/bin/bash

for i in 7

EXAMPLE 1: THE FOR LOOP#!/bin/bashfor i in 7 9 2 3

9 2 3 4 5
do
echo $i
done
CSCI 330

- The Unix System

Слайд 40 EXAMPLE 2: USING THE FOR LOOP
#!/bin/bash
# compute the

EXAMPLE 2: USING THE FOR LOOP#!/bin/bash# compute the average weekly temperaturefor

average weekly temperature

for num in 1 2 3 4

5 6 7
do
read -p "Enter temp for day $num: " Temp
let TempTotal=$TempTotal+$Temp
done

let AvgTemp=$TempTotal/7
echo "Average temperature: " $AvgTemp

CSCI 330 - The Unix System


Слайд 41 LOOPING OVER ARGUMENTS
simplest form will iterate over all

LOOPING OVER ARGUMENTSsimplest form will iterate over all command line arguments:	#!

command line arguments:

#! /bin/bash
for parm
do
echo

$parm
done

CSCI 330 - The Unix System


Слайд 42 SELECT COMMAND
Constructs simple menu from word list
Allows user

SELECT COMMANDConstructs simple menu from word listAllows user to enter a

to enter a number instead of a word
User enters

sequence number corresponding to the word

Syntax:
select WORD in LIST
do
RESPECTIVE-COMMANDS
done

Loops until end of input, i.e. ^d (or ^c)

CSCI 330 - The Unix System


Слайд 43 SELECT EXAMPLE
#! /bin/bash
select var in alpha beta gamma
do

SELECT EXAMPLE#! /bin/bashselect var in alpha beta gammado  echo $vardonePrints:CSCI

echo $var
done

Prints:

CSCI 330 - The Unix System
1)

alpha
2) beta
3) gamma
#? 2
beta
#? 4
#? 1
alpha

Слайд 44 SELECT DETAIL
PS3 is select sub-prompt
$REPLY is user input

SELECT DETAILPS3 is select sub-prompt$REPLY is user input (the number)#! /bin/bashPS3=

(the number)

#! /bin/bash
PS3="select entry or ^D: "
select var in

alpha beta
do
echo "$REPLY = $var"
done

CSCI 330 - The Unix System

Output:
select ...
1) alpha
2) beta
? 2
2 = beta
? 1
1 = alpha


Слайд 45 SELECT EXAMPLE
#!/bin/bash
echo "script to make files private"
echo "Select

SELECT EXAMPLE#!/bin/bashecho

file to protect:"

select FILENAME in *
do
echo "You picked

$FILENAME ($REPLY)"
chmod go-rwx "$FILENAME"
echo "it is now private"
done

CSCI 330 - The Unix System


Слайд 46 BREAK AND CONTINUE
Interrupt for, while or until

BREAK AND CONTINUEInterrupt for, while or until loopThe break statement

loop
The break statement
transfer control to the statement AFTER

the done statement
terminate execution of the loop
The continue statement
transfer control to the statement TO the done statement
skip the test statements for the current iteration
continues execution of the loop

CSCI 330 - The Unix System


Слайд 47 THE BREAK COMMAND
while [ condition ]
do
cmd-1

THE BREAK COMMANDwhile [ condition ]do cmd-1 break cmd-ndoneecho

break
cmd-n
done
echo "done"
CSCI 330 - The Unix

System

This iteration is over and there are no more iterations


Слайд 48 THE CONTINUE COMMAND
while [ condition ]
do
cmd-1

THE CONTINUE COMMANDwhile [ condition ]do cmd-1 continue cmd-ndoneecho

continue
cmd-n
done
echo "done"
CSCI 330 - The Unix

System

This iteration is over; do the next iteration


Слайд 49 EXAMPLE:
for index in 1 2 3 4 5

EXAMPLE:for index in 1 2 3 4 5 6 7 8

6 7 8 9 10
do
if

[ $index –le 3 ]; then
echo "continue"
continue
fi
echo $index
if [ $index –ge 8 ]; then
echo "break"
break
fi
done

CSCI 330 - The Unix System


Слайд 50



DONE !
BASH SHELL PROGRAMMING
Sequence
Decision:
if-then-else
case
Repetition
do-while, repeat-until
for
select
Functions
Traps
CSCI

DONE !BASH SHELL PROGRAMMINGSequenceDecision:if-then-elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps CSCI 330 - The Unix System still to come

330 - The Unix System

still to come


Слайд 51 SHELL FUNCTIONS
A shell function is similar to a

SHELL FUNCTIONSA shell function is similar to a shell scriptstores a

shell script
stores a series of commands for execution later
shell

stores functions in memory
shell executes a shell function in the same shell that called it
Where to define
In .profile
In your script
Or on the command line
Remove a function
Use unset built-in

CSCI 330 - The Unix System


Слайд 52 SHELL FUNCTIONS
must be defined before they can be

SHELL FUNCTIONSmust be defined before they can be referencedusually placed at

referenced
usually placed at the beginning of the script

Syntax:

function-name ()

{
statements
}

CSCI 330 - The Unix System


Слайд 53 EXAMPLE: FUNCTION
#!/bin/bash

funky () {
# This is

EXAMPLE: FUNCTION#!/bin/bash funky () { 	# This is a simple function

a simple function
echo "This is a funky function."


echo "Now exiting funky function."
}

# declaration must precede call:

funky

CSCI 330 - The Unix System


Слайд 54 EXAMPLE: FUNCTION
#!/bin/bash
fun () { # A somewhat more

complex function.
JUST_A_SECOND=1
let i=0
REPEATS=30
echo "And now

the fun really begins."
while [ $i -lt $REPEATS ]
do
echo "-------FUNCTIONS are fun-------->"
sleep $JUST_A_SECOND
let i+=1
done
}
fun

CSCI 330 - The Unix System


Слайд 55 FUNCTION PARAMETERS
Need not be declared
Arguments provided via function

FUNCTION PARAMETERSNeed not be declaredArguments provided via function call are accessible

call are accessible inside function as $1, $2, $3,



$# reflects number of parameters
$0 still contains name of script
(not name of function)

CSCI 330 - The Unix System


Слайд 56 EXAMPLE: FUNCTION WITH PARAMETER
#! /bin/sh
testfile() {
if [

EXAMPLE: FUNCTION WITH PARAMETER#! /bin/shtestfile() { if [ $# -gt 0

$# -gt 0 ]; then
if [[

-f $1 && -r $1 ]]; then
echo $1 is a readable file
else
echo $1 is not a readable file
fi
fi
}

testfile .
testfile funtest

CSCI 330 - The Unix System


Слайд 57 EXAMPLE: FUNCTION WITH PARAMETERS
#! /bin/bash
checkfile() {
for

EXAMPLE: FUNCTION WITH PARAMETERS#! /bin/bashcheckfile() { for file do  if

file
do
if [ -f "$file"

]; then
echo "$file is a file"
else
if [ -d "$file" ]; then
echo "$file is a directory"
fi
fi
done
}
checkfile . funtest

CSCI 330 - The Unix System


Слайд 58 LOCAL VARIABLES IN FUNCTIONS
Variables defined within functions are

LOCAL VARIABLES IN FUNCTIONSVariables defined within functions are global,	i.e. their values

global,
i.e. their values are known throughout the entire shell

program

keyword “local” inside a function definition makes referenced variables “local” to that function

CSCI 330 - The Unix System


Слайд 59 EXAMPLE: FUNCTION
#! /bin/bash

global="pretty good variable"

foo () {

EXAMPLE: FUNCTION#! /bin/bashglobal=

local inside="not so good variable"

echo $global
echo $inside
global="better variable"
}

echo $global
foo
echo $global
echo $inside

CSCI 330 - The Unix System


Слайд 60 HANDLING SIGNALS
Unix allows you to send a signal

HANDLING SIGNALSUnix allows you to send a signal to any process-1

to any process

-1 = hangup kill -HUP 1234
-2 =

interrupt with ^C kill -2 1235
no argument = terminate kill 1235
-9 = kill kill -9 1236
-9 cannot be blocked

list your processes with
ps -u userid

CSCI 330 - The Unix System


Слайд 61 SIGNALS ON LINUX
% kill -l
1) SIGHUP

SIGNALS ON LINUX% kill -l 1) SIGHUP  2) SIGINT

2) SIGINT 3) SIGQUIT

4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX

^C is 2 - SIGINT

CSCI 330 - The Unix System


Слайд 62 HANDLING SIGNALS
Default action for most signals is to

HANDLING SIGNALSDefault action for most signals is to end processterm: signal

end process
term: signal handler

Bash allows to install custom signal

handler
Syntax:
trap 'handler commands' signals

Example:
trap 'echo do not hangup' 1 2

CSCI 330 - The Unix System


Слайд 63 EXAMPLE: TRAP HANGUP
#! /bin/bash
# kill -1 won’t kill

EXAMPLE: TRAP HANGUP#! /bin/bash# kill -1 won’t kill this process# kill

this process
# kill -2 will

trap 'echo dont hang up'

1

while true
do
echo "try to hang up"
sleep 1
done

CSCI 330 - The Unix System


Слайд 64 EXAMPLE: TRAP MULTIPLE SIGNALS
#! /bin/sh
# plain kill or

EXAMPLE: TRAP MULTIPLE SIGNALS#! /bin/sh# plain kill or kill -9 will

kill -9 will kill this
trap 'echo 1' 1
trap 'echo

2' 2

while true; do
echo -n .
sleep 1
done

CSCI 330 - The Unix System


Слайд 65 EXAMPLE: REMOVING TEMP FILES
#! /bin/bash
trap 'cleanup; exit' 2

cleanup

EXAMPLE: REMOVING TEMP FILES#! /bin/bashtrap 'cleanup; exit' 2cleanup () {

() {
/bin/rm -f /tmp/tempfile.$$.?
}

for i

in 1 2 3 4 5 6 7 8
do
echo "$i.iteration"
touch /tmp/tempfile.$$.$i
sleep 1
done
cleanup

CSCI 330 - The Unix System


Слайд 66 RESTORING DEFAULT HANDLERS
trap without a command list will

RESTORING DEFAULT HANDLERStrap without a command list will remove a signal

remove a signal handler
Use this to run a signal

handler once only

#! /bin/sh
trap 'justonce' 2
justonce() {
echo "not yet"
trap 2 # now reset it
}

while true; do
echo -n "."
sleep 1
done

CSCI 330 - The Unix System


Слайд 67 DEBUG SHELL PROGRAMS
Debugging is troubleshooting errors that may

DEBUG SHELL PROGRAMSDebugging is troubleshooting errors that may occur during the

occur during the execution of a program/script
The following two

commands can help you debug a bash shell script:
echo
use explicit output statements to trace execution
set

CSCI 330 - The Unix System


Слайд 68 DEBUGGING USING “SET”
The “set” command is a shell

DEBUGGING USING “SET”The “set” command is a shell built-in commandhas options

built-in command
has options to allow flow of execution
–v option

prints each line as it is read
–x option displays the command and its arguments
–n checks for syntax errors
options can turned on or off
To turn on the option: set -xv
To turn off the options: set +xv

Options can also be set via she-bang line
#! /bin/bash -xv

CSCI 330 - The Unix System


  • Имя файла: bash-programming-csci-330-the-unix-system.pptx
  • Количество просмотров: 128
  • Количество скачиваний: 0