P. 1
L_6

L_6

|Views: 3|Likes:
Published by ScribberTiger

More info:

Published by: ScribberTiger on Jul 03, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as ODP, PDF, TXT or read online from Scribd
See more
See less

04/19/2014

pdf

text

original

Intro to Unix/Linux

Fall 2010 ~ Eric Meyer

Lecture 6 Introduction to Shell Scripting Programming.

Lesson A
Using the UNIX Shell as a Scripting Language

2

Objectives
 Understand the program development cycle using a high-

level computer language and UNIX shell scripts

 Compare the shells to determine the best choice for

creating scripts

 Learn about shell variables, operators, and wildcard

characters

 Write simple shell scripts to illustrate programming logic

3

The Program Development Cycle
 The program development cycle is the process of

developing an application
 The first step in the cycle is to create program

specifications
 The second step in the cycle is to create the program

design
 The third step is developing the code, which is written,

tested, and debugged

4

5

Using High-Level Languages
 High-level languages are computer languages that use

English-like expressions

 Example are; COBOL, C, C++  A program’s high-level language statements are stored in a

file called the source file, which programmers creates using editors

 In order to execute, high-level source files must be

converted into a low-level machine language file

6

Using High-Level Languages
 A compiler is a program that converts source files into

executable machine-language files

 The complier reads the lines of code the programmer wrote

in the source file and converts them to the appropriate machine language instructions

 If 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

7

Using UNIX Shell Scripts
 Unlike high-level language programs, shell scripts do not

have to be converted into machine language by a compiler

 The UNIX shell acts as an interpreter when reading script

files

 Interpreters read statements in script files and immediately

translate them into executable instructions and cause them to run

8

Using UNIX Shell Scripts
 After creating shell script, the OS is instructed that the file is

an executable shell script via the chmod command

 When the file is designated as executable, you may it run in

one of many ways:

 Type the script name at the command prompt after

updating the path variable

 If the script is in the current directory, proceed its name

at the prompt with a dot slash (./) at the command prompt

 If not in the current directory, specify the absolute path

9

The Programming Shell

All Linux versions use the Bash shell as the default

10

Variables
 Variables are symbolic names that represent values stored

in memory

 Three types of variables are:
 Configuration variables store information about the setup

of the OS session

 Environment variables hold information about your login  Shell variables are created at the command prompt or in

shell scripts and are used to temporarily store information

11

Variables

Use the printenv command to see a list of environment variables
12

13

14

15

Variables
To set: example=one To see: echo $example To make part of the environment: export example To remove: unsetenv example

16

Shell Operators
 Bash shell operators are in three groups:
 Defining and Evaluating operators are used to set a

variable to a value and to check variable values

The equal sign (=) is an example

 Arithmetic operators are used to perform mathematical

equations

The plus sign (+) is an example

 Redirecting and piping operators are used to specify

input and output data specifications

The greater than sign (>) is an example
17

Shell Operators

18

More About Wildcard Characters
 Shell scripts often use wildcard characters  Wildcard characters are intended to match filenames and

words

 Question mark (?) matches exactly one character  Asterisk (*) matches zero or more characters  [chars] defines a class of characters, the glob pattern

matches any singles character in the class

19

Shell Logic Structures
 Four basic logic structures needed for program development

are:
 Sequential logic  User input  Decision logic  Looping logic  Case logic

20

Sequential Logic
 commands are executed in the order in which they appear

in the script

 break in sequence occurs when a branch instruction

changes the flow of execution by redirecting to another location in the script

21

User input
 Script can read user data  Command: read variable

 reads user input and assigns text to variable

22

User input
Command: read var1 var2 var3

 reads 3 words and assigns 3 variables  Last variable contains rest of input line

23

User input
Command: read –p “enter name: “ name

 Prompts user, then reads input and assigns to variable

24

User input example

25

Decision Logic
 Enables your script to execute statement(s)

only if a certain condition is true

 Condition:
 result of a command  Comparison of variables or values

if statement
26

If statement
 Syntax:

if [ condition ] then statements else statements fi

27

Decision Logic example

28

Nested Decision Logic

29

Looping Logic
 A control structure repeats until some condition exists or

some action occurs

 Two 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

30

For Loop
 Syntax

for var in list do statements done

31

For Loop example
Program control structures can be entered from the command line

32

For loop in script

33

Loop with wildcard

34

While Loop
 Syntax

while [ condition ] do statements done

35

Looping Logic
The while loop tests repeatedly for a matching condition

36

Looping Logic
While loops can serve as data-entry forms

37

While loop to enter data

38

Case Logic
 The case logic structure simplifies the selection from a list of

choices

 It allows the script to perform one of many actions,

depending on the value of a variable

 Two semicolons (;;) terminate the actions taken after the

case matches what is being tested

39

Case statement
 Syntax:

case $variable in “pattern1”) statements ;; “pattern2”) statements ;; esac
40

Case example

41

Case Logic

42

Debugging a Shell Script
 Shell script will not execute if there is an error in one or

more commands

 sh has options for debugging
 sh -v

displays lines of script as they are read by the interpreter
 sh -x

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

43

Debugging a Shell Script
View the script line by line as it is running to help locate errors

44

Lesson B
Creating and Completing the Corporate Phone Application

45

Objectives
 Create screen-management scripts

 Use the trap command

 Enter and test shell scripts to print the phone records, view

the contents of the corp_phone file, and add new phone records to the file

46

Using Shell Scripting to Create a Menu
 A menu is a good example of a shell script that employs the

four basic logic structures

 A significant feature of the menu script is the screen

presentation which should be as appealing and user-friendly as possible

47

tput command
 tput clear
 clear the screen

 tput cup r c
 position cursor to row and column  ex: tput cup 0 0

tput cup 20 10
 bold=`tput smso`  offbold=`tput rmso`

48

Example

tput clear; tput cup 10 15; echo “Hello”; tput cup 20 0
49

Creating a Menu
tput can be used to help create data entry screens

50

Creating a Menu

51

Creating a Menu
tput can be used to help create user menus

52

Creating a Menu

53

The trap Command
 used to guard against abnormal termination of script
 user ^C  OS intervention

 normal: remove temporary file  example:

trap ’rm ~/tmp/*’ 2 15

54

Creating the corp_phones File
The grep command is useful when building script applications by extracting data from files

55

Creating 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

56

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

57

Multi-xxxx

The UNIX Operating System provides an environment in which multiple “processes” can run concurrently – Multitasking or multiprogramming: the ability to run multiple programs on the same machine concurrently – Multiprocessing: the ability to use multiple processors on the same machine – Multiprocessing sometimes is also used to indicate that multiple concurrent processes can execute at the same time in a single processor environment UNIX supports both multiprogramming and multiprocessing (in both senses) – This is implemented through the process abstraction – More recently supporting Light Weight Processes and Threads has also become the norm
58

In traditional systems a process executes a single sequence of instructions in an address space. – The program counter (PC) is a special hardware register that tracks the current instruction that is to be execute – In UNIX, many processes are active at the same time and the OS provides some aspects of a virtual machine • Processes have their own registers and memory, but rely on the OS for I/O, device control and interacting with other processes – Processes: • Run in a virtual address space • Content for resources such as processor(s), memory, and peripheral devices • All of the above is managed by the OS the memory management system; the I/O system; the process management and scheduling system, and the Interprocess Communication system (IPC)
59

The Process Abstraction

More about a Process

Processes are created by the OS, typically by the fork command. – The process that calls fork is the parent and the new process is the child. – The child inherits a replica of the parent’s address space and is essentially a clone. Both continue to execute the identical program. Fork returns the child’s process id to the parent, and the value 0 to the child. – The exec system call loads another program and starts running this (typically in the child process). States of a Process – Initial, ready to run, running (in user mode or kernel mode), asleep, stopped, zombie (upon exit). Finally, when all resources are freed by the parent, the process is terminated or no longer exists.
60

Basic job control commands
ps: displays information about processes options:[-a] all processes for “everyone” [-l] longer version [u] current user report [-aux] more complete listing &: running a process (job) in the background example: pp3 & jobs: shows you all your background processes fg: puts a background job into the foreground CTRL-z: stops a process bg: puts a job into the background CTRL-c: kill the foreground job kill: kill a specific job (-9 typically kills most processes)
61

More job control commands
sleep: causes the current process to sleep for the time indicated. example: sleep 15; ls sleep 10; ls & stop: can be used to stop a specific job running in the background nice: run a job with a lower (nicer) priority level ranges are -20 (highest) to +20 (lowest). Default is 0. Default nice is usually 4. example: nice +10 pp3

62

Running more than one shell

By using the csh command, you can start another shell running. You can change directories etc in this shell, and go back to your original shell by using the suspend command. Example csh (get a new shell, do some work, say change directory) suspend (go back to your original shell) (work in your original shell) jobs (get the job number of the csh shell, say 1) fg 1 (bring the csh shell into the foreground) exit (terminate the csh shell and go back to original)
63

Editing and Running

Typical way of developing a program – Edit a program, say with vi, then save and exit – Run the program; determine errors – Edit the program by starting another vi session, – Etc. Alternate Paradigm – Edit a program, say with vi, the write the file (w) and use CTRL-z to stop the vi process – Run you program; determine errors – Bring back vi by using fg 1 – Etc.
64

X Windows
 Standard Toolkit and protocol to build GUI
 Allows for drawing and moving of windows  Allow mouse interaction and keyboard

 Designed to be used over the network  Based on a client server model
 X Server communicates with various client programs  Accepts graphical output and sends back user input.

 Can be used over a secure network through Tunneling.

Starting X Windows
 Linux environments have native X support.
 ssh -Y diablo.cs.fsu.edu: Enables trusted X11

forwarding.
 Microsoft Windows need a helper X program.
 Xwin32: http://www.starnet.com/

None free – has a trial version

 Cygwin: http://www.cygwin.com/

Free open source Unix windows port.

 SSH Client Enable Tunneling (Windows)  Xterm – X Terminal is a think client that runs on X server

Chapter Summary
 A high-level language uses English-like expressions and

must be converted into a low-level language before being executed

 The shell interprets shell scripts  UNIX shell script instructions do not need to be written

from scratch, they are chosen from an inventory of executable commands shells, and bash is the default environment, and shell

 Linux shells are derived from the UNIX Bourne, Korn and C  UNIX employs three types of variables: configuration,

67

Chapter Summary
 The shell supports numerous operators, including many

for performing arithmetic operations

 Wildcard characters are used in shell scripts  The logic structures supported by the shell are sequential,

decision, looping and case placement on the screen

 The tput command can be used to manage cursor  Programmers and system administrators often customize

the .bashrc file to suit their needs

68

Chapter Summary
 Aliases, used to simplify commonly used commands, can

be entered into the .bashrc
 Use the trap command to remove temporary files after the

script exits
 The grep command serves a key role in the development

of shell scripts by allowing searching and retrieving data from files
 The awk command serves as an effective and easy-to-use

tool for generating reports

69

70

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->