P. 1


|Views: 3|Likes:
Published by ScribberTiger

More info:

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


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





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


 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


 Write simple shell scripts to illustrate programming logic


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

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

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

tested, and debugged



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


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


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


 Interpreters read statements in script files and immediately

translate them into executable instructions and cause them to run


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


The Programming Shell

All Linux versions use the Bash shell as the default


 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



Use the printenv command to see a list of environment variables




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


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


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

Shell Operators


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


 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


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

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


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


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

 reads user input and assigns text to variable


User input
Command: read var1 var2 var3

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


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

 Prompts user, then reads input and assigns to variable


User input example


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

If statement
 Syntax:

if [ condition ] then statements else statements fi


Decision Logic example


Nested Decision Logic


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



For Loop
 Syntax

for var in list do statements done


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


For loop in script


Loop with wildcard


While Loop
 Syntax

while [ condition ] do statements done


Looping Logic
The while loop tests repeatedly for a matching condition


Looping Logic
While loops can serve as data-entry forms


While loop to enter data


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


 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


Case statement
 Syntax:

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

Case example


Case Logic


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


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


Lesson B
Creating and Completing the Corporate Phone Application


 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


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


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`



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

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


Creating a Menu


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


Creating a Menu


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


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


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


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



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

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)

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.

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)

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


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)

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.

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

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


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


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



You're Reading a Free Preview

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