Chapter 6 Introduction to Shell Script Programming.

45
Chapter 6 Introduction to Shell Script Programming

Transcript of Chapter 6 Introduction to Shell Script Programming.

Chapter 6

Introduction to Shell Script Programming

Guide to UNIX Using Linux, Third Edition

2

Objectives

Using shell variables, operators, and wildcard charactersUsing shell logic structuresEmploy shell scripting to create a menuUse commands to help debug shell scriptsCustomizing your personal environmentUsing the trap commandDevelop a menu-based application

Guide to UNIX Using Linux, Third Edition

3

The Program Development Cycle

The program development cycle is the process of developing an application 1st step is to create program

specifications 2nd step is to create the program

design 3rd step is developing the code, which

is written, tested, and debugged

Guide to UNIX Using Linux, Third Edition

4

The Program Development Cycle

Guide to UNIX Using Linux, Third Edition

5

Using High-Level Languages

High-level languages are computer languages that use English-like expressionsExamples are; COBOL, C, C++High-level language statements are stored in a source file, which programmers create using an editor

Guide to UNIX Using Linux, Third Edition

6

High-level source files must be converted into a low-level machine language file A compiler is a program that converts source files into executable machine-language filesIf a source file contains syntax errors, it cannot be converted into an executable file A programmer must correct these

errors before the program can be run

Using High-Level Languages

Guide to UNIX Using Linux, Third Edition

7

Using UNIX/Linux Shell Scripts

Unlike high-level language programs, shell scripts do not have to be converted into machine languageThe UNIX/Linux shell acts as an interpreter when reading script filesInterpreters read statements in script files and immediately translate them into executable instructions and run them

Guide to UNIX Using Linux, Third Edition

8

Using UNIX/Linux Shell Scripts

After creating shell script, the OS is instructed that the file is an executable shell script via the chmod commandScript files can be run in several ways: Set the path variable and type the

script name at the command prompt Type ./filename if script is in current

directory Type the script name preceded by the

full path

Guide to UNIX Using Linux, Third Edition

9

Prototyping an Application

A prototype is a running model of your application Less detail, less design time than a

full application Shows potential without full

programming effortShell scripts can be used to prototype applications that will later be moved to compiled languages

Guide to UNIX Using Linux, Third Edition

10

Using Comments

Comments are important!Provide useful documentation to both the programmer and to others who need to understand or debug the codeTo use, start comment line with a #

Guide to UNIX Using Linux, Third Edition

11

The Programming Shell

All Linux versions use the Bash shell as the default

Guide to UNIX Using Linux, Third Edition

12

Variables

Variables are symbolic names that represent values stored in memoryThree types of variables: Configuration variables store information

about the setup of the OS Environment variables hold information

about your login session Shell variables are created at the

command prompt or in shell scripts and are used to temporarily store information

Guide to UNIX Using Linux, Third Edition

13

Variables

Use the printenv variable to see a list of environment variables.

You can also use env

Look at the man pages. What is different between the two commands?

Turn to page 195 (2nd Ed.) or page 269 (3rd Ed.)

Guide to UNIX Using Linux, Third Edition

14

Environment and Configuration Variables (continued)

Use the printenv variable to see a list of environment variables

Guide to UNIX Using Linux, Third Edition

15

Environment and Configuration Variables

Guide to UNIX Using Linux, Third Edition

16

Environment and Configuration Variables

Guide to UNIX Using Linux, Third Edition

17

Environment and Configuration Variables

Guide to UNIX Using Linux, Third Edition

18

Environment and Configuration Variables

Guide to UNIX Using Linux, Third Edition

19

Shell Variables

Shell Variables are variables that you can define and manipulate for use with program commands in a shellObserve basic guidelines for handling and naming shell variables I recommend that you use all UPPERCASE

characters when naming your variables

Guide to UNIX Using Linux, Third Edition

20

Shell Variables

Variables are handled differently depending on the syntaxType: echo $USERNAME echo “$USERNAME” echo ’$USERNAME’ echo `$USERNAME`

Guide to UNIX Using Linux, Third Edition

21

Shell Operators

Bash shell operators are in four groups: Defining operators Evaluating operators Arithmetic operators Redirection operators

Guide to UNIX Using Linux, Third Edition

22

Defining Operators

Used to assign a value to a variableMost common is = (equal sign)Use quotation marks with stringsBackquote says execute the command inside the backquotes and store the result in the variable

Guide to UNIX Using Linux, Third Edition

23

Evaluating Operators

Used for determining the contents of a variableecho $variablename will show the value of variablenameDouble quotes can be used, but not single quotes

Guide to UNIX Using Linux, Third Edition

24

Arithmetic Operators

Guide to UNIX Using Linux, Third Edition

25

Arithmetic Operators (continued)

Regular mathematical precedence rules apply to arithmetic operatorsTo store arithmetic values in a variable, use let statement let x=6+4*2 echo $x

Guide to UNIX Using Linux, Third Edition

26

Redirection Operators

The > redirection operator overwrites an existing file-o noclobber option of set command will prevent overwriting

Guide to UNIX Using Linux, Third Edition

27

Exporting Shell Variables to the Environment

Shell scripts cannot automatically access variables created and assigned On the command line By other scripts

Make variables global in your environment by using the export command

Guide to UNIX Using Linux, Third Edition

28

Modifying the PATH Variable

PATH variable controls where your shell will look for shell scriptsYou can add directories to your PATH Special directories for scripts Your current working directory

Guide to UNIX Using Linux, Third Edition

29

More About Wildcard Characters

Shell scripts often use wildcard charactersWildcard characters are called glob characters and are a part of glob patternsGlob patterns are intended to match filenames and words Question mark (?) matches one character Asterisk (*) matches zero or more

characters [chars] defines a class of characters, the

glob pattern matches any character in the class

Guide to UNIX Using Linux, Third Edition

30

Shell Logic Structures

Four basic logic structures needed for program development are: Sequential logic Decision logic Looping logic Case logic

Guide to UNIX Using Linux, Third Edition

31

Sequential Logic

Commands are executed in the order in which they appear in the script or programThe only break in this sequence comes when a branch instruction changes the flow of execution by redirecting to another location in the script or programUsed for simple, straightforward command sequences

Guide to UNIX Using Linux, Third Edition

32

Decision Logic

Enables your script or program to execute a statement or series of statements only if a certain condition existsIn many cases, the condition depends upon the result of a command or on a comparisonThe if statement is the primary decision-making control structure in this type of logic

Guide to UNIX Using Linux, Third Edition

33

Looping Logic

A control structure repeats until some condition exists or some action occursTwo common looping mechanisms: for loops cycle through a range of

values until the last in a set of values is reached

The while loop cycles as long as a particular condition exists

Guide to UNIX Using Linux, Third Edition

34

Looping Logic (continued)

The for loop repeats for however many values there are in the specified set of values

Guide to UNIX Using Linux, Third Edition

35

Program control structures can be entered from the command lineWildcard characters can be used in loopsThe while loop is set up to test repeatedly for a matching conditionThe while loop is used when code must be repeatedly executed an undetermined number of times

Looping Logic (continued)

Guide to UNIX Using Linux, Third Edition

36

Case Logic

The case logic structure simplifies the selection from a list of choicesIt allows the script to perform one of many actions, depending on the value of a variableTwo semicolons (;;) terminate the actions taken after the case matches what is being tested

Guide to UNIX Using Linux, Third Edition

37

Using Shell Scripting to Create a Menu

Often useful to create a menu that branches to specific shell scriptsThe tput command is useful when creating menus Can initialize the terminal display to place

text and prompts in specific locations and respond to the user

Guide to UNIX Using Linux, Third Edition

38

Debugging a Shell Script

A shell script will not execute if there is an error in one or more commandsRunning a shell script using sh enables quick debugging of problems sh -v option displays lines of code in the

script as they are read by the interpreter sh -x option displays the command and

its arguments line by line as they are run

Guide to UNIX Using Linux, Third Edition

39

Customizing YourPersonal Environment

When programming and shell scripting, customizing your environment by modifying the initial settings in the login scripts provides many benefitsLogin scripts run just after logging inSetting up personal bin directories and modify editor defaults are common customizations

Guide to UNIX Using Linux, Third Edition

40

Customizing Your Personal Environment

An alias is a name that represents another command The .bashrc file in your home directory is used to establish customizations that take effect at each loginThe .bashrc script is executed each time a shell is generated, such as when shell scripts are run

Guide to UNIX Using Linux, Third Edition

41

The trap Command

The trap command causes a shell program to automatically remove temporary files created when shell scripts runProgrammers often set up a subdirectory to store temporary files, and when a script file exits, trap removes the filesHaving files removed from a temporary directory like this is considered “good housekeeping”

Guide to UNIX Using Linux, Third Edition

42

Putting It All Together in an Application

Applications require you to: Assign and manage variables Use shell operators Employ shell logic structures Use additional wildcard characters Use tput for managing screen

initialization Use trap to clean up temporary files

Will use these skills to build a shell script application in Hands-on Project

Guide to UNIX Using Linux, Third Edition

43

Chapter Summary

A high-level language uses English-like expressions and must be converted into a low-level language before being executedThe shell interprets shell scriptsLinux shells are derived from the UNIX Bourne, Korn and C shells, and bash is the default

Guide to UNIX Using Linux, Third Edition

44

UNIX/Linux uses three types of variables: configuration, environment, and shellShell operators include defining, evaluating, arithmetic, and redirectionWildcard characters are used in shell scriptsThe logic structures supported are: sequential, decision, looping and case

Chapter Summary (continued)

Guide to UNIX Using Linux, Third Edition

45

The tput command manages cursor placement on the screenProgrammers and system administrators often customize the .bashrc fileAliases simplify common commands can be entered into the .bashrc Use the trap command to remove temporary files after the script exits

Chapter Summary (continued)