Title: CS 205 Linux
1CS 205 - Linux
- Chapter 6
- Introduction to Shell Script Programming
2Objectives
- Understanding the program development cycle.
- Comparing UNIX/Linux shells for creating scripts.
- Use shell variables, operators, and wildcard
characters. - Use shell logic structures.
- Employ shell scripting to create a menu. Use
commands to help debug shell scripts. - Explain ways to customize your personal
environment. - Use the trap command.
- Develop a menu-based application.
Practice Exercises
Check out the menu system under www.elmhurst.edu.
Additional References
None
Scripts include the commands previously discussed
in the course as well as additional commands for
logic and variable control.
3Previewing the Application
- Shell variables temporarily store values in
memory for use by a shell script. - Symbolic name consists of letters, numbers, or
characters. - References the contents of a variable.
- Often reflects a variables purpose or contents.
- Shell scripts support many shell script
operators. - Shell scripts support logic structures.
- Sequential, decision, looping, and case logic.
- Also called control structures
Practice Exercises
None.
Additional References
None
Virtually all programming and scripting languages
have the same logic structures. The trick to
learning a new language is understanding the
syntax for the logic structures.
4Program Development Cycle
- Program development cycle process of developing
an application. - Step 1 create program specifications
- Step 2 begin design process
- Create file formats, screen layouts, and
algorithms - Step 3 write the actual code
- Step 4 test and debug
Some books focus on pseudo code. Personal view
Pseudo code moves programming from the programmer
to the systems analysts and makes no sense as
documentation.
5High-Level Languages versus Scripts
- High-Level Languages rely on source code that is
compiled into machine language - Add 1 to Counter. (Cobol)
- counter counter 1 (C)
- counter counter 1 (Fortran, Basic)
- Scripts rely on source code that is interpreted
and converted to machine language one statement
at a time, while it is executed. - chmod x filename
- High-Level Languages and Scripts can both have
syntax errors and logic errors. - Syntax errors are invalid statements, e.g. typos.
- Logic errors produce unexpected results.
Practice Exercises
None.
Additional References
None
High-Level Languages create applications that are
more efficient but the trade-off is execution
time. You have to balance development time with
execution time.
6Using Comments in Scripts
- Comments begin with a in UNIX/Linux scripts.
Practice Exercises
None.
Script Name pact By Your initials
Date November 2009 Purpose Create temporary
file, pnum, to hold the count of the number of
projects each programmer is working on. The
pnum file consists of prog_num and count
fields
cut -d -f4 project sort uniq
-c awk printf "s s\n",2,1 gt pnum cut
prog_num, pipe output to sort to remove
duplicates and get count for prog/projects.
output file with prog_number followed by count
Additional References
None
Comments should provide additional documentation
for the developer supporting the application
they should not just provide a description of the
code.
7Using Comments in Scripts
- Some examples
- Script name, author(s), creation date, and
purpose. - Modification date(s) and purpose of each of them,
i.e. Change Control Log. - Purpose and types of variables used.
- Files that are accessed, created, or modified.
- How logic structures work.
- Purpose of shell functions.
- How complex lines of code work.
- The reasons for including specific commands
Practice Exercises
None.
Additional References
None
As you gain programming experience supporting
other developers applications, you will begin to
see what you wish you knew about an application.
8Programming Shells
- Three shells come with most Linux installations.
Different shells have slightly different syntax.
Practice Exercises
None.
Additional References
None
We will focus on the Bash shell. C programmers
may wish to use the C shell but should be aware
of the differences between shells if someone else
is to support their applications.
9Variables
- Configuration variables store information about
the setup of OS. They are typically not modified
after they are set up. - Environment variables store initial values can be
changed as needed. - Shell variables are created at command line or in
a shell script and are useful for temporarily
storing information.
Practice Exercises
None
Additional References
None
By convention, configuration and environment
variables are upper case and shell variables are
lower case. This is not a rule, but a convention.
10Environment and Configuration Variables
- Use printenv to view list of your current
environment and configuration variables. - Use set, without any options to see a list of all
variables, configuration, environment, and shell.
Practice Exercises
Try the printenv and set commands.
Additional References
None
Remember what you learned about printing.To print
the value of an environment variable, precede it
with a , e.g. echo LOGNAME.
11Environment and Configuration Variables
12Environment and Configuration Variables
13Environment and Configuration Variables
- Basic guidelines for handling shell variables
- Omit spaces when you assign a variable without
using single/double quotation marks around value. - To assign a variable that must contain spaces,
enclose value in or . - To reference a variable, use a in front of it
or enclose it in . - Use to refer to a specific value in an array.
- Export a shell variable to make the variable
available to other scripts. - To make a shell variable read-only readonly
fname. - Avoid using dollar sign in variable names.
- Use descriptive names.
- Use capitalization appropriately and
consistently. - If a variable name is to consist of two or more
words, use underscores between the words.
Practice Exercises
Try the set command to see if any shell variables
are set. Remember, environment and configuration
variables are also displayed with set.
Additional References
None
Most programmers prefer to use all lower case for
shell variables. Programmers from other
backgrounds may elect to use different standards,
e.g. normal case.
14Shell Operators
- Defining Operators assign a value to a variable.
- NAMEBecky
- NAME"Becky J. Zubrow"
- LIST ls
- Evaluating Operators display the contents of a
variable. - echo NAME
- echo "NAME"
- echo 'NAME'
- Arithmetic and Relational Operators perform math
and logical comparisons. - Redirection Operators change values of variables
or redirect output of commands. - set -o noclobber ltEntergt
- cat new_file gt old_file ltEntergt
- cat new_file gt old_file ltEntergt
Practice Exercises
None.
Additional References
None
Do not worry about the classification of
operators, just focus on what each of them does.
15Arithmetic and Relational Operators
Practice Exercises
None.
Additional References
None
Like logic control syntax, another trick to
leaning a new programming language is to learn
the syntax for arithmetic and relational
operators.
16Arithmetic and Relational Operators
- let is a built-in Bash shell command to assign a
value to a variable.
Practice Exercises
None.
Additional References
None
Anyone familiar with the original BASIC
programming language from Dartmouth College in
the 1960s? It used Let to assign a value to a
variable.
17Redirection Operators
- set is used to display variables and to set
various shell options, e.g. you can use it to
prevent files from being overwritten with the cat
command.
Practice Exercises
None.
Additional References
None
The set command is especially useful during
debugging. You can use the n option to debug a
script without changing data.
18Exporting Shell Variables
- Shell variables are local to the shell unless
they are made global by exporting them. - Exported shell variables are local to a specific
Linux session and are deleted when you log off.
Practice Exercises
None.
Additional References
None
If you need a variable to exist from session to
session, make it an environment variable in your
logon script.
19PATH Environment Variable
- The PATH environment variable provides Linux with
a list of directories where commands can be
found. - Commands that are separate Linux files must be in
directories that are part of the path or the
complete path must be specified to execute the
command. - When you created an executable file with the
chmod command, you executed it by preceding the
command with ./ to indicate that the command was
in the current working directory. - To see the directories in the path
- echo PATH
- To add the current working directory to the path
- PATHPATH .
- (The dot at the end of the path indicates the
current working directory.)
Practice Exercises
Display the contents of the path. Add the working
directory to the path and redisplay the path.
Additional References
None
The concept of a path is the same for Windows.
The sequence of directories in the path indicates
a search sequence.
20Wildcard Characters
- Wildcard characters are known as glob characters
- Shell processes glob characters in unquoted
arguments for file name generation - Glob characters are part of glob patterns
- Intended to match file names and words
- Special constructions that appear in glob
patterns - ?
-
- chars
- Example more chap1-3 ltEntergt
Practice Exercises
Create three files with called chap1, chap2, and
chap3 with the touch command then try the ls l
command with the wildcard character to see
what happens.
Additional References
None
The and ? wildcard characters are common to
Windows and Linux. The wildcard characters
allow you to repeat commands with specific sets
of characters instead of any characters.
21Shell Logic Structures
- The four basic logic structures needed for
program development - Sequential logic
- Decision logic
- Looping logic
- Case logic
Practice Exercises
None
Additional References
None
Can you give examples of each of the basic logic
structures in Cobol, C, C?
22Sequential Logic
- Commands are executed in the order in which they
appear in the script or program.
Practice Exercises
None
Script Name practivity By
MP Date November 2009 Purpose Generate
Programmer Activity Status Report
cut -d -f4 project sort uniq -c awk
printf "s s \n",2,1 gt pnum cut -d
-f1-4 programmer sort -t 0 -1 uniq gt
pnn join -t -a1 -j1 1 -j2 1 pnn pnum gt pactrep
Print the report awk BEGIN FS ""
print "\tProgrammer Activity Status Report\n"
"date" getline d printf "\t s\n",d
print "Prog \t--Name-- Projects\n"
print "
\n" printf "-s\t-12.12s -12.12s
s\td\n", 1, 2, 3, 4, 5
pactrep remove all the temporary files rm pnum
pnn pactrep
Additional References
None
The scripts for Chapter 5 are examples of
sequential logic.
23Decision Logic
- Decision Logic uses the basic If Then Else
construct common to programming.
Practice Exercises
None
echo -n "What is your favorite vegetable? " read
veg_name if "veg_name" "broccoli" then
echo "Broccoli is a healthy choice." else if
"veg_name" "carrots" then echo
"Carrots are great for you." else echo
"Don't forget to eat your broccoli also."
fi fi
Additional References
None
Note that the test is in square brackets an that
the if statement ends with fi. Recall the
comments on understanding the syntax. What
language uses Endif?
24Looping Logic
- Looping Logic uses the basic For and While
construct common to programming.
Practice Exercises
None
for USERS in john ellen tom becky eli jill do
echo USERS done
for file in chap1234 do more file done
echo -n "Try to guess my favorite color " read
guess while "guess" ! "red" do echo "No,
not that one. Try again. " read guess done
Additional References
None
Note that the first example loops for each of the
values of USERS listed in the statement.
25Case Logic
- Case Logic uses the basic Case construct common
to some but not all programming languages.
Practice Exercises
None
echo -n "Enter your favorite color " read
color case "color" in "blue") echo "As in My
Blue Heaven." "yellow") echo "As in the
Yellow Sunset." "red") echo "As in Red
Rover, Red Rover." "orange") echo "As in
Autumn has shades of Orange." ) echo
"Sorry, I do not know that color." esac
Additional References
None
Note that the case command ends with case spelled
backwards, i.e. esac. Who came up with this
backwards nonsense anyway?
26Using Shell Scripts to Create Menus
- The tput command can be used to clear the screen,
position the cursor on the screen and to
determine how wide the user has configured the
screen.
Practice Exercises
Login to www.elmhurst.edu. What commands might
they have used to create the menus? Create a
script to clear the screen the execute the echo
PATH command at row 10, column 20.
Additional References
None
The ability to determine the number of columns,
i.e. the width of the screen, can be very useful
to complex programs that wish to customize the
display.
27Debugging Scripts
- Recall that you need to make a script executable
to execute it with the command ./filename? - The sh command allows you to execute script
without changing it to an executable file.
Practice Exercises
Create a simple script and execute it with the sh
command.
Additional References
None
Build a script by testing its components
individually then check the overall syntax with
the sh command before you run a script that might
alter files.
28The trap command
- Recall that you need to make a script executable
to execute it with the command ./filename?
Practice Exercises
None.
Additional References
None
xxx
29Putting it all Together
- Create a multifunctional application
- Assign and manage variables.
- Use shell operators.
- Employ shell logic structures.
- Use additional wildcard characters.
- Use tput for screen initialization and text
placement. - Use trap to clean up temporary files.
- For additional practice, see Projects 6-15
through 6-20.
30Summary
- A shell interprets UNIX/Linux shell scripts.
- Scripts are not interpreted, not compiled.
- Shell scripts can be created with any text
editor. - Linux shells are derived from the UNIX Bourne,
Korn, and C shells. - UNIX/Linux employ three types of variables
- Configuration, environment, and shell.
- The shell supports many operators.
- Use wildcard characters in shell scripts.
- Logic structures supported by the shell
- Sequential, decision, looping, and case.
- Use tput to manage cursor placement.
- Use trap inside a script file to remove temporary
files after the script file has been run (exited).
31Command Summary
32Command Summary