Date post: | 20-Jan-2016 |
Category: |
Documents |
Upload: | hilary-fields |
View: | 222 times |
Download: | 2 times |
Chapter SixChapter Six
Introduction to Shell Script Introduction to Shell Script ProgrammingProgramming
22
Lesson ALesson A
Using the UNIX Shell as aUsing the UNIX Shell as a
Scripting LanguageScripting Language
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
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
55
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
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
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
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
1010
The Programming ShellThe Programming Shell
All Linux versions use the Bash shell as the default
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
1212
VariablesVariables
Use the printenv command to see a list of environment variables
1313
1414
1515
1616
VariablesVariables
To set:
example=one
To see:
echo $example
To make part of the environment:
export example
To remove:
unsetenv example
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
1818
Shell OperatorsShell Operators
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
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
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
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
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
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
2525
User input exampleUser input example
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
2727
If statementIf statement
Syntax:Syntax:
if [ condition ]if [ condition ]
thenthen
statementsstatements
elseelse
statementsstatements
fifi
2828
Decision Logic exampleDecision Logic example
2929
Nested Decision LogicNested Decision Logic
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
3131
For LoopFor Loop
SyntaxSyntax
for var in listfor var in list
dodo
statementsstatements
donedone
3232
For Loop exampleFor Loop exampleProgram control structures can be entered from the command line
3333
For loop in scriptFor loop in script
3434
Loop with wildcardLoop with wildcard
3535
While LoopWhile Loop
SyntaxSyntax
while [ condition ]while [ condition ]
dodo
statementsstatements
donedone
3636
Looping LogicLooping LogicThe while loop tests repeatedly for a matching condition
3737
Looping LogicLooping Logic
While loops can serve as data-entry forms
3838
While loop to enter dataWhile loop to enter data
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
4040
Case statementCase statement
Syntax:Syntax:
case $variable incase $variable in““pattern1”)pattern1”)
statementsstatements;;;;
““pattern2”)pattern2”)statementsstatements;;;;
esacesac
4141
Case exampleCase example
4242
Case LogicCase Logic
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
4444
Debugging a Shell ScriptDebugging a Shell Script
View the script line by line as it is running to help locate errors
4545
Lesson BLesson B
Creating and Completing theCreating and Completing the
Corporate Phone ApplicationCorporate Phone Application
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
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
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`
4949
ExampleExample
tput clear; tput cup 10 15;
echo “Hello”; tput cup 20 0
5050
Creating a MenuCreating a Menu
tput can be used to help create data entry screens
5151
Creating a MenuCreating a Menu
5252
Creating a MenuCreating a Menu
tput can be used to help create user menus
5353
Creating a MenuCreating a Menu
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
5555
Creating the corp_phones FileCreating the corp_phones File
The grep command is useful when building script applications by extracting data from files
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
5757
Creating the phoneadd Shell Creating the phoneadd Shell ScriptScript
The phoneadd script allows you to add new records to the corp_phones file
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
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
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
6161