Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell...

70
Shell Script Shell Script Programming Programming

Transcript of Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell...

Shell Script ProgrammingShell Script Programming

22

Using UNIX Shell ScriptsUsing UNIX Shell Scripts

Unlike high-level language programs, shell Unlike high-level language programs, shell scripts do not have to be converted into machine scripts do not have to be converted into machine language by a compilerlanguage by a compiler

The UNIX shell acts as an interpreter when The UNIX shell acts as an interpreter when reading script filesreading script files

Interpreters read statements in script files and Interpreters read statements in script files and immediately translate them into executable immediately translate them into executable instructions and cause them to runinstructions and cause them to run

33

Using UNIX Shell ScriptsUsing UNIX Shell Scripts

After creating shell script, the OS is instructed After creating shell script, the OS is instructed that the file is an executable shell script via the that the file is an executable shell script via the chmod commandchmod command

When the file is designated as executable, you When the file is designated as executable, you may run it in one of many ways:may run it in one of many ways:– Type the script name at the command prompt after Type the script name at the command prompt after

updating the path variableupdating the path variable– If the script is in the current directory, proceed its If the script is in the current directory, proceed its

name at the prompt with a dot slash (./)name at the prompt with a dot slash (./)– If not in the current directory, specify the absolute If not in the current directory, specify the absolute

path at the command promptpath at the command prompt

44

Ensuring the Correct Shell Ensuring the Correct Shell Runs the ScriptRuns the Script

In Unix there is more than one shell !In Unix there is more than one shell !– examples: bash, tcsh, kshexamples: bash, tcsh, ksh

need to ensure that correct shell runs the scriptneed to ensure that correct shell runs the script

different shells use different programming different shells use different programming constructsconstructs

Convention: first line of a script states which Convention: first line of a script states which executable should run scriptexecutable should run script

Example: Example:

#! /bin/sh#! /bin/sh

55

VariablesVariables

Variables are symbolic names that represent Variables are symbolic names that represent values stored in memoryvalues stored in memory

Three types of variables are:Three types of variables are:– Configuration variables store information about the Configuration variables store information about the

setup of the OSsetup of the OS– Environment variables hold information about your Environment variables hold information about your

login sessionlogin session– Shell variables are created at the command prompt or Shell variables are created at the command prompt or

in shell scripts and are used to temporarily store in shell scripts and are used to temporarily store informationinformation

66

VariablesVariables

To set:

example=one

To see:

echo $example

To make part of the environment:

export example

To remove:

unsetenv example

77

VariablesVariables

Use the printenv command to see a list of environment variables

88

Some VariablesSome Variables

HOME

home directory

USER

user name

PATH

list of command directories

PWD

current directory

99

Shell OperatorsShell Operators

Bash shell operators are in three groups:Bash shell operators are in three groups:– Defining and EvaluatingDefining and Evaluating operators are used to set a operators are used to set a

variable to a value and to check variable valuesvariable to a value and to check variable valuesThe equal sign (=) is an exampleThe equal sign (=) is an example

– ArithmeticArithmetic operators are used to perform operators are used to perform mathematical equationsmathematical equations

The plus sign (+) is an exampleThe plus sign (+) is an example

– Redirecting and pipingRedirecting and piping operators are used to specify operators are used to specify input and output data specificationsinput and output data specifications

The greater than sign (>) is an exampleThe greater than sign (>) is an example

1010

Shell OperatorsShell Operators

1111

Wildcard CharactersWildcard Characters

Shell scripts often use wildcard charactersShell scripts often use wildcard characters

Wildcard characters are intended to match Wildcard characters are intended to match filenames and wordsfilenames and words– Question mark (?) matches exactly one Question mark (?) matches exactly one

charactercharacter– Asterisk (*) matches zero or more characters Asterisk (*) matches zero or more characters – [chars] defines a class of characters, the glob [chars] defines a class of characters, the glob

pattern matches any singles character in the pattern matches any singles character in the classclass

1212

Shell Logic StructuresShell Logic Structures

Four basic logic structures needed for Four basic logic structures needed for program development are:program development are:– Sequential logicSequential logic– User inputUser input– Decision logicDecision logic– Looping logicLooping logic– Case logicCase logic

1313

Sequential LogicSequential Logic

commands are executed in the order in commands are executed in the order in which they appear in the scriptwhich they appear in the script

break in sequence occurs when a branch break in sequence occurs when a branch instruction changes the flow of execution instruction changes the flow of execution by redirecting to another location in the by redirecting to another location in the script script

1414

User inputUser input

Script can read user dataScript can read user data

Command: Command: read variableread variable

reads user input and assigns text to reads user input and assigns text to variablevariable

1515

User inputUser input

Command: Command: read var1 var2 var3read var1 var2 var3

reads 3 words and assigns 3 reads 3 words and assigns 3 variablesvariables

Last variable contains rest of input Last variable contains rest of input lineline

1616

User inputUser input

Command: Command:

read –p “enter name: “ nameread –p “enter name: “ name

Prompts user, then reads input and Prompts user, then reads input and assigns to variableassigns to variable

1717

User input exampleUser input example

1818

Decision LogicDecision Logic

Enables your script to execute statement(s) Enables your script to execute statement(s)

only if a certain condition is trueonly if a certain condition is true

Condition:Condition:– result of a command result of a command – Comparison of variables or valuesComparison of variables or values

ifif statement statement

1919

If statementIf statement

Syntax:Syntax:

if [ condition ]if [ condition ]

thenthen

statementsstatements

elseelse

statementsstatements

fifi

2020

Decision Logic exampleDecision Logic example

2121

Nested Decision LogicNested Decision Logic

2222

Looping LogicLooping Logic

A control structure repeats until some A control structure repeats until some condition exists or some action occurscondition exists or some action occurs

Two common looping mechanisms:Two common looping mechanisms:– For loops cycle through a range of values until For loops cycle through a range of values until

the last in a set of values is reachedthe last in a set of values is reached– The while loop cycles as long as a particular The while loop cycles as long as a particular

condition existscondition exists

2323

For LoopFor Loop

SyntaxSyntax

for var in listfor var in list

dodo

statementsstatements

donedone

2424

For Loop exampleFor Loop exampleProgram control structures can be entered from the command line

2525

For loop in scriptFor loop in script

2626

Loop with wildcardLoop with wildcard

2727

While LoopWhile Loop

SyntaxSyntax

while [ condition ]while [ condition ]

dodo

statementsstatements

donedone

2828

Looping LogicLooping LogicThe while loop tests repeatedly for a matching condition

2929

Looping LogicLooping Logic

While loops can serve as data-entry forms

3030

While loop to enter dataWhile loop to enter data

3131

Case LogicCase Logic

The case logic structure simplifies the The case logic structure simplifies the selection from a list of choicesselection from a list of choices

It allows the script to perform one of many It allows the script to perform one of many actions, depending on the value of a actions, depending on the value of a variablevariable

Two semicolons (;;) terminate the actions Two semicolons (;;) terminate the actions taken after the case matches what is being taken after the case matches what is being testedtested

3232

Case statementCase statement

Syntax:Syntax:

case $variable incase $variable in““pattern1”)pattern1”)

statementsstatements;;;;

““pattern2”)pattern2”)statementsstatements;;;;

esacesac

3333

Case exampleCase example

3434

Case LogicCase Logic

3535

Debugging a Shell ScriptDebugging a Shell Script

Shell script will not execute if there is an error in Shell script will not execute if there is an error in one or more commandsone or more commands

sh has options for debuggingsh has options for debugging– sh -v sh -v

displays lines of script as they are read by the displays lines of script as they are read by the interpreterinterpreter

– sh -x sh -x

displays the command and its arguments line by line displays the command and its arguments line by line as they are runas they are run

3636

Debugging a Shell ScriptDebugging a Shell Script

View the script line by line as it is running to help locate errors

3737

Using Shell Scripting toUsing Shell Scripting toCreate a MenuCreate a Menu

A menu is a good example of a shell script A menu is a good example of a shell script that employs the four basic logic that employs the four basic logic structuresstructures

A significant feature of the menu script is A significant feature of the menu script is the screen presentation which should be the screen presentation which should be as appealing and user-friendly as possibleas appealing and user-friendly as possible

3838

tput commandtput command

tput cleartput clear– clear the screenclear the screen

tput cup r ctput cup r c– position cursor to row and columnposition cursor to row and column– ex: tput cup 0 0ex: tput cup 0 0

tput cup 20 10tput cup 20 10

bold=`tput smso`bold=`tput smso`

offbold=`tput rmso`offbold=`tput rmso`

3939

ExampleExample

tput clear; tput cup 10 15;

echo “Hello”; tput cup 20 0

4040

Creating a MenuCreating a Menu

tput can be used to help create data entry screens

4141

Creating a MenuCreating a Menu

4242

Creating a MenuCreating a Menu

tput can be used to help create user menus

4343

Creating a MenuCreating a Menu

4444

The trap CommandThe trap Command

used to guard against abnormal used to guard against abnormal termination of scripttermination of script– user ^Cuser ^C– OS interventionOS intervention

normal: remove temporary filenormal: remove temporary file

example:example:

trap ’rm ~/tmp/*’ 2 15trap ’rm ~/tmp/*’ 2 15

4545

The awk CommandThe awk Command

Allows simple formatting of outputAllows simple formatting of output– Reads input line by lineReads input line by line– Line contains fields (need field separator)Line contains fields (need field separator)– Use C printf command to format outputUse C printf command to format output

4646

Example: corp_phonesExample: corp_phones

awk -F ':' ‘{printf("%-12s %-10s %10s\n",$2,$3,$1)}’ corp_phones

4747

Shell script: phoneaddShell script: phoneadd

The phoneadd script allows to add new records to the corp_phones file

4848

Shell script: phoneaddShell script: phoneadd

4949

Complete script: phmenuComplete script: phmenu

5050

Script parametersScript parameters

Command line invocation may list Command line invocation may list parametersparameters

Example:Example:

myscript one two threemyscript one two three

Available inside scripts as $1, $2, $3Available inside scripts as $1, $2, $3

5151

Parameter exampleParameter example

5252

Script ParametersScript Parameters

5353

More Script ParametersMore Script Parameters

5454

Numeric variablesNumeric variables

Let command defines integer variables Let command defines integer variables with numeric valueswith numeric values

Example:Example:

let i=1let i=1

let i=5*i-2 let i=5*i-2

Let command allows simple numeric Let command allows simple numeric calculationscalculations

5555

Using the test CommandUsing the test Command

Bash shell uses test command to:Bash shell uses test command to:– perform relational tests with integersperform relational tests with integers– test and compare stringstest and compare strings– check if a file exists and what type of file it ischeck if a file exists and what type of file it is– perform Boolean testsperform Boolean tests

Test command is standard Unix commandTest command is standard Unix command

Is used in bash for if and while statementsIs used in bash for if and while statements

5656

Using the test commandUsing the test command

Syntax:Syntax:

test some-expressiontest some-expression

[ some-expression ][ some-expression ]

Indicates result via exit statusIndicates result via exit status– 0 is true, 1 is false0 is true, 1 is false

To get exit status:To get exit status:

echo $?echo $?

5757

Relational Integer TestsRelational Integer Tests

5858

String TestsString Tests

5959

Testing FilesTesting Files

6060

Performing Boolean TestsPerforming Boolean Tests

6161

Using the test CommandUsing the test Command

6262

QuotingQuoting

Double quotesDouble quotesexample: example: text=“hello world”text=“hello world”

echo “here it is: $text”echo “here it is: $text”Single quotesSingle quotesexample: example: text=‘one two three’text=‘one two three’

echo “here it is: $text”echo “here it is: $text”Execution quoteExecution quoteexample: example: text=`date`text=`date`

echo “here it is: $text”echo “here it is: $text”

6363

Review: sedReview: sed

Can be used to remove lines from a fileCan be used to remove lines from a file

Syntax:Syntax:

sed ‘/pattern/d’ file1 > file2sed ‘/pattern/d’ file1 > file2

Removes all lines which match the Removes all lines which match the patternpattern from file1 from file1

6464

Deleting Phone RecordsDeleting Phone Records

The menu has been updated to allow for deleting a phone record

6565

Deleting Phone RecordsDeleting Phone Records

Examine the corp_phones file before deleting a record

6666

Deleting Phone RecordsDeleting Phone Records

The sed command is behind the delete option

6767

Deleting Phone RecordsDeleting Phone Records

The record is no longer in the file

6868

Shell functionsShell functions

Used to group recurring codeUsed to group recurring code

Syntax:Syntax:

functionname() {functionname() {

commandscommands

}}

6969

Shell function exampleShell function example

datenow() {datenow() {

datedate

}}

it=`datenow`it=`datenow`

echo $itecho $it

7070

Shell function parametersShell function parameterscheckfile() {checkfile() {echo “Checking: $1”echo “Checking: $1”if [ -f “$1” ]if [ -f “$1” ]thenthen

echo “$1 is a file”echo “$1 is a file”elseelse

if [ -d “$1” ]if [ -d “$1” ]thenthen

echo “$1 is a directory”echo “$1 is a directory”fifi

fifi}}checkfile phmenucheckfile phmenu