Chapter Six Introduction to Shell Script Programming.

61
Chapter Six Chapter Six Introduction to Shell Introduction to Shell Script Programming Script Programming

Transcript of Chapter Six Introduction to Shell Script Programming.

Page 1: Chapter Six Introduction to Shell Script Programming.

Chapter SixChapter Six

Introduction to Shell Script Introduction to Shell Script ProgrammingProgramming

Page 2: Chapter Six Introduction to Shell Script Programming.

22

Lesson ALesson A

Using the UNIX Shell as aUsing the UNIX Shell as a

Scripting LanguageScripting Language

Page 3: Chapter Six Introduction to Shell Script Programming.

33

ObjectivesObjectives

Understand the program development cycle Understand the program development cycle using a high-level computer language and UNIX using a high-level computer language and UNIX shell scriptsshell scripts

Compare the shells to determine the best choice Compare the shells to determine the best choice for creating scriptsfor creating scripts

Learn about shell variables, operators, and Learn about shell variables, operators, and wildcard characterswildcard characters

Write simple shell scripts to illustrate Write simple shell scripts to illustrate programming logicprogramming logic

Page 4: Chapter Six Introduction to Shell Script Programming.

44

The Program Development The Program Development CycleCycle

The program development cycle is the The program development cycle is the process of developing an applicationprocess of developing an application– The first step in the cycle is to create program The first step in the cycle is to create program

specificationsspecifications– The second step in the cycle is to create the The second step in the cycle is to create the

program designprogram design– The third step is developing the code, which is The third step is developing the code, which is

written, tested, and debuggedwritten, tested, and debugged

Page 5: Chapter Six Introduction to Shell Script Programming.

55

Page 6: Chapter Six Introduction to Shell Script Programming.

66

Using High-Level Using High-Level LanguagesLanguages

High-level languages are computer languages High-level languages are computer languages that use English-like expressionsthat use English-like expressions

Example are; COBOL, C, C++Example are; COBOL, C, C++

A program’s high-level language statements are A program’s high-level language statements are stored in a file called the source file, which stored in a file called the source file, which programmers creates using editorsprogrammers creates using editors

In order to execute, high-level source files must In order to execute, high-level source files must be converted into a low-level machine language be converted into a low-level machine language filefile

Page 7: Chapter Six Introduction to Shell Script Programming.

77

Using High-Level Using High-Level LanguagesLanguages

A compiler is a program that converts source A compiler is a program that converts source files into executable machine-language filesfiles into executable machine-language files

The complier reads the lines of code the The complier reads the lines of code the programmer wrote in the source file and programmer wrote in the source file and converts them to the appropriate machine converts them to the appropriate machine language instructionslanguage instructions

If a source file contains syntax errors, it cannot If a source file contains syntax errors, it cannot be converted into an executable filebe converted into an executable file– A programmer must correct these errors before the A programmer must correct these errors before the

program can be run program can be run

Page 8: Chapter Six Introduction to Shell Script Programming.

88

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

Page 9: Chapter Six Introduction to Shell Script Programming.

99

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 it run in one of many ways:may it run 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

Page 10: Chapter Six Introduction to Shell Script Programming.

1010

The Programming ShellThe Programming Shell

All Linux versions use the Bash shell as the default

Page 11: Chapter Six Introduction to Shell Script Programming.

1111

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

Page 12: Chapter Six Introduction to Shell Script Programming.

1212

VariablesVariables

Use the printenv command to see a list of environment variables

Page 13: Chapter Six Introduction to Shell Script Programming.

1313

Page 14: Chapter Six Introduction to Shell Script Programming.

1414

Page 15: Chapter Six Introduction to Shell Script Programming.

1515

Page 16: Chapter Six Introduction to Shell Script Programming.

1616

VariablesVariables

To set:

example=one

To see:

echo $example

To make part of the environment:

export example

To remove:

unsetenv example

Page 17: Chapter Six Introduction to Shell Script Programming.

1717

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

Page 18: Chapter Six Introduction to Shell Script Programming.

1818

Shell OperatorsShell Operators

Page 19: Chapter Six Introduction to Shell Script Programming.

1919

More About Wildcard More About Wildcard CharactersCharacters

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

Page 20: Chapter Six Introduction to Shell Script Programming.

2020

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

Page 21: Chapter Six Introduction to Shell Script Programming.

2121

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

Page 22: Chapter Six Introduction to Shell Script Programming.

2222

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

Page 23: Chapter Six Introduction to Shell Script Programming.

2323

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

Page 24: Chapter Six Introduction to Shell Script Programming.

2424

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

Page 25: Chapter Six Introduction to Shell Script Programming.

2525

User input exampleUser input example

Page 26: Chapter Six Introduction to Shell Script Programming.

2626

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

Page 27: Chapter Six Introduction to Shell Script Programming.

2727

If statementIf statement

Syntax:Syntax:

if [ condition ]if [ condition ]

thenthen

statementsstatements

elseelse

statementsstatements

fifi

Page 28: Chapter Six Introduction to Shell Script Programming.

2828

Decision Logic exampleDecision Logic example

Page 29: Chapter Six Introduction to Shell Script Programming.

2929

Nested Decision LogicNested Decision Logic

Page 30: Chapter Six Introduction to Shell Script Programming.

3030

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

Page 31: Chapter Six Introduction to Shell Script Programming.

3131

For LoopFor Loop

SyntaxSyntax

for var in listfor var in list

dodo

statementsstatements

donedone

Page 32: Chapter Six Introduction to Shell Script Programming.

3232

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

Page 33: Chapter Six Introduction to Shell Script Programming.

3333

For loop in scriptFor loop in script

Page 34: Chapter Six Introduction to Shell Script Programming.

3434

Loop with wildcardLoop with wildcard

Page 35: Chapter Six Introduction to Shell Script Programming.

3535

While LoopWhile Loop

SyntaxSyntax

while [ condition ]while [ condition ]

dodo

statementsstatements

donedone

Page 36: Chapter Six Introduction to Shell Script Programming.

3636

Looping LogicLooping LogicThe while loop tests repeatedly for a matching condition

Page 37: Chapter Six Introduction to Shell Script Programming.

3737

Looping LogicLooping Logic

While loops can serve as data-entry forms

Page 38: Chapter Six Introduction to Shell Script Programming.

3838

While loop to enter dataWhile loop to enter data

Page 39: Chapter Six Introduction to Shell Script Programming.

3939

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

Page 40: Chapter Six Introduction to Shell Script Programming.

4040

Case statementCase statement

Syntax:Syntax:

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

statementsstatements;;;;

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

esacesac

Page 41: Chapter Six Introduction to Shell Script Programming.

4141

Case exampleCase example

Page 42: Chapter Six Introduction to Shell Script Programming.

4242

Case LogicCase Logic

Page 43: Chapter Six Introduction to Shell Script Programming.

4343

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

Page 44: Chapter Six Introduction to Shell Script Programming.

4444

Debugging a Shell ScriptDebugging a Shell Script

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

Page 45: Chapter Six Introduction to Shell Script Programming.

4545

Lesson BLesson B

Creating and Completing theCreating and Completing the

Corporate Phone ApplicationCorporate Phone Application

Page 46: Chapter Six Introduction to Shell Script Programming.

4646

ObjectivesObjectives

Create screen-management scriptsCreate screen-management scripts

Use the trap commandUse the trap command

Enter and test shell scripts to print the Enter and test shell scripts to print the phone records, view the contents of the phone records, view the contents of the corp_phone file, and add new phone corp_phone file, and add new phone records to the filerecords to the file

Page 47: Chapter Six Introduction to Shell Script Programming.

4747

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

Page 48: Chapter Six Introduction to Shell Script Programming.

4848

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`

Page 49: Chapter Six Introduction to Shell Script Programming.

4949

ExampleExample

tput clear; tput cup 10 15;

echo “Hello”; tput cup 20 0

Page 50: Chapter Six Introduction to Shell Script Programming.

5050

Creating a MenuCreating a Menu

tput can be used to help create data entry screens

Page 51: Chapter Six Introduction to Shell Script Programming.

5151

Creating a MenuCreating a Menu

Page 52: Chapter Six Introduction to Shell Script Programming.

5252

Creating a MenuCreating a Menu

tput can be used to help create user menus

Page 53: Chapter Six Introduction to Shell Script Programming.

5353

Creating a MenuCreating a Menu

Page 54: Chapter Six Introduction to Shell Script Programming.

5454

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

Page 55: Chapter Six Introduction to Shell Script Programming.

5555

Creating the corp_phones FileCreating the corp_phones File

The grep command is useful when building script applications by extracting data from files

Page 56: Chapter Six Introduction to Shell Script Programming.

5656

Creating the corp_phones FileCreating the corp_phones File

Using awk speeds development in that it can select fields from many records and display them in a specified format on the screen

Page 57: Chapter Six Introduction to Shell Script Programming.

5757

Creating the phoneadd Shell Creating the phoneadd Shell ScriptScript

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

Page 58: Chapter Six Introduction to Shell Script Programming.

5858

Chapter SummaryChapter Summary

A high-level language uses English-like A high-level language uses English-like expressions and must be converted into a low-expressions and must be converted into a low-level language before being executedlevel language before being executedThe shell interprets shell scriptsThe shell interprets shell scriptsUNIX shell script instructions do not need to be UNIX shell script instructions do not need to be written from scratch, they are chosen from an written from scratch, they are chosen from an inventory of executable commands inventory of executable commands Linux shells are derived from the UNIX Bourne, Linux shells are derived from the UNIX Bourne, Korn and C shells, and bash is the defaultKorn and C shells, and bash is the defaultUNIX employs three types of variables: UNIX employs three types of variables: configuration, environment, and shellconfiguration, environment, and shell

Page 59: Chapter Six Introduction to Shell Script Programming.

5959

Chapter SummaryChapter Summary

The shell supports numerous operators, The shell supports numerous operators, including many for performing arithmetic including many for performing arithmetic operationsoperationsWildcard characters are used in shell scriptsWildcard characters are used in shell scriptsThe logic structures supported by the shell are The logic structures supported by the shell are sequential, decision, looping and casesequential, decision, looping and caseThe tput command can be used to manage The tput command can be used to manage cursor placement on the screencursor placement on the screenProgrammers and system administrators often Programmers and system administrators often customize the .bashrc file to suit their needscustomize the .bashrc file to suit their needs

Page 60: Chapter Six Introduction to Shell Script Programming.

6060

Chapter SummaryChapter Summary

Aliases, used to simplify commonly used Aliases, used to simplify commonly used commands, can be entered into the .bashrc commands, can be entered into the .bashrc

Use the trap command to remove temporary Use the trap command to remove temporary files after the script exitsfiles after the script exits

The grep command serves a key role in the The grep command serves a key role in the development of shell scripts by allowing development of shell scripts by allowing searching and retrieving data from filessearching and retrieving data from files

The awk command serves as an effective and The awk command serves as an effective and easy-to-use tool for generating reportseasy-to-use tool for generating reports

Page 61: Chapter Six Introduction to Shell Script Programming.

6161