A Guide to Unix Using Linux Fourth Edition
Chapter 7Advanced Shell Programming
A Guide to Unix Using Linux, Fourth Edition 2
Objectives
• Perform program design and analysis using flowcharts and pseudocode
• Use techniques to ensure a script is employing the correct shell
• Set the default shell
• Configure Bash login and logout scripts
• Set defaults for the vi editor
• Use the test command for programming functions
A Guide to Unix Using Linux, Fourth Edition 3
Objectives (continued)
• Format record output
• Delete records using a script
• Set up a quick screen-clearing technique
• Create a program algorithm to solve a cursor-repositioning problem
• Develop and test a program to eliminate duplicate records
• Create shell functions and use them in a program
A Guide to Unix Using Linux, Fourth Edition 4
Understanding Program Design and Analysis
• Design process:– Second step in program development cycle
• After creating the specifications for program
– Develop computer program by analyzing best way to achieve desired results
– Two popular and proven analysis tools:• Flowchart
• Pseudocode
A Guide to Unix Using Linux, Fourth Edition 5
Flowcharting
• Flowchart– Logic diagram– Uses set of standard symbols– Visually explains sequence of
events from start of process to its end point
– Documents:• Processes• Procedures• Program sequence
A Guide to Unix Using Linux, Fourth Edition 6
Flowcharting (continued)
A Guide to Unix Using Linux, Fourth Edition 7
Writing Pseudocode
• After creating a flowchart, you write pseudocode– Creates a model that you can later use as a basis for
a real program
Display "What is your favorite vegetable? " on the screenEnter data into veg_nameIf veg_name is equal to "broccoli"Then Display "Broccoli is a healthy choice." on the screenElse Display "Don’t forget to eat your broccoli also." on thescreenEnd If
A Guide to Unix Using Linux, Fourth Edition 8
A Guide to Unix Using Linux, Fourth Edition 9
Ensuring the Correct Shell Runs the Script
• UNIX/Linux users can choose their shell of preference
• To ensure that the correct shell is used to interpret your script:– Include command that sets the particular shell to use
on the first line of the script• #!/bin/bash
A Guide to Unix Using Linux, Fourth Edition 10
Setting the Default Shell
• Shell set up by default is established by system administrator– /etc/passwd filetrbrown:x:500:500:Thomas Brown:/home/trbrown:/bin/bash
• To edit /etc/passwd file:– Use vi or Emacs
• Must be very careful!
• Make a backup copy first
– Use a GUI• e.g., User Manager tool in GNOME desktop, YaST
A Guide to Unix Using Linux, Fourth Edition 11
Setting the Default Shell (continued)
A Guide to Unix Using Linux, Fourth Edition 12
Using Bash Login and Logout Scripts
• In Bash, two scripts run when you log in:– .bash_profile and .bashrc
• Edit files with a text editor
• Unlike .bash_profile, .bashrc is also run each time you start a subshell
• /etc/.bashrc, /etc/bashrc, or /etc/bash.bashrc files set system defaults– Not always available
• .bash_logout file (in your home directory) executes commands when user logs out
A Guide to Unix Using Linux, Fourth Edition 13
Using Bash Login and Logout Scripts (continued)
A Guide to Unix Using Linux, Fourth Edition 14
Setting Defaults for Using the vi Editor
• .exrc used to automatically set up vi environment– Located in your home directory– Example:
set numberset tabstop=3set shell=/bin/bash
A Guide to Unix Using Linux, Fourth Edition 15
Using the test Command
A Guide to Unix Using Linux, Fourth Edition 16
Performing Relational Integer Tests with the test Command
• Exit status: numeric value that command returns to OS when it finishes– Interpreting exit status for test command:
• 0 (zero) test result is true
• 1 test result is false
• Use echo $? to view most recent exit status
A Guide to Unix Using Linux, Fourth Edition 17
Performing Relational Integer Tests with the test Command (continued)
A Guide to Unix Using Linux, Fourth Edition 18
Performing String Tests with the test Command
• These tests are useful in scripts to test contents of variables– Example: ensure that a variable contains a specific
value
A Guide to Unix Using Linux, Fourth Edition 19
Testing Files with the test Command
A Guide to Unix Using Linux, Fourth Edition 20
Performing Boolean Tests with the test Command
• Boolean operator: logical operator that symbolizes AND, OR, or NOT to evaluate a relationship– Result of evaluation is either true or false
• Examples:– test expression1 -a expression2– test expression1 -o expression2– test !expression
A Guide to Unix Using Linux, Fourth Edition 21
Formatting Record Output
• To format record output, use translate utility, tr
• Two examples:1) tr [a-z] [A-Z] < counters– Sends contents of counters file as input to tr – Then, converts lowercase characters to uppercase
2) cat names | tr ":" " "– Sends output of cat to tr – Pipes (|) contents of names file to tr– tr replaces each occurrence of “:” with a space
A Guide to Unix Using Linux, Fourth Edition 22
Deleting Phone Records
• sed takes contents of input file and applies actions to file’s contents– Actions provided as options and arguments– Results are sent to standard output device
• Simple way to delete a phone record:– Use -d option
Enter phone numberUse sed -d to delete the matching phone number and output toa temporary file, fConfirm acceptanceIf the output is accepted, copy the temporary file f back tocorp_phones (overlaying it)
A Guide to Unix Using Linux, Fourth Edition 23
Clearing the Screen
A Guide to Unix Using Linux, Fourth Edition 24
Creating an Algorithm to Place the Cursor
Read information into field2 While field2 equals "-" Move cursor to position of previous field, field1 Clear current information displayed in field1 Read new information into field1 If field1 = "q" Then Exit program End If Move cursor to position of field2 Read information into field2End While
tput cup 5 18; read lname while test "$lname" = "-" do tput cup 4 18; echo " " tput cup 4 18; read phonenum tput cup 5 18; read lname done
A Guide to Unix Using Linux, Fourth Edition 25
Protecting Against Entering Duplicate Data
• A program should always check its input to ensure the user has entered acceptable information– Input validation
A Guide to Unix Using Linux, Fourth Edition 26
A Guide to Unix Using Linux, Fourth Edition 27
Using Shell Functions
• Shell function: group of commands stored in memory and assigned a name– Shell scripts can use function name to execute the
commands– Use shell functions to isolate reusable code sections
• Reduce typing and debugging time– Example:
datenow(){date}
A Guide to Unix Using Linux, Fourth Edition 28
Defining a Function from the Command Line
• You can define functions from the command line:
• However, functions are usually stored in script files – Loaded into memory when you log in
• Arguments are passed to functions in the same manner as any other shell procedure:
[martin@localhost ~]$ datenow() <Enter>> { <Enter>> date <Enter>> } <Enter>[martin@localhost ~]$
[martin@localhost ~]$ datenow "Today’s date and time are:"Today’s date and time are:Mon Feb 9 21:49:45 MST 2009
A Guide to Unix Using Linux, Fourth Edition 29
Creating Functions Inside Shell Scripts
• Example: a shell script called .myfuncs
• You may start .myfuncs from your .bash_profile or .bashrc login script, or the command line
sort_name(){sort -k 2 -t: corp_phones}sort_job(){sort -k 6 -t: corp_phones}sort_dept(){sort -k 5 -t: corp_phones}
A Guide to Unix Using Linux, Fourth Edition 30
Troubleshooting a Shell Script
• Some tips to help you troubleshoot a script:– Ensure script has execute permissions– Be certain first line of script specifies shell to use– Use the sh -n, -v, and -x troubleshooting options– Look for typographic errors– Look for errors in the use of particular characters
• ;, ‘, `, ‘’, “”, #, <, >
– Check for syntax errors in the use of commands– Look for the use of command options that are not
supported in your distribution of UNIX/Linux– Check initial and exit value of looping logic
A Guide to Unix Using Linux, Fourth Edition 31
Summary
• Two most popular and proven analysis tools: flowchart and pseudocode
• Have the first line in a script file specify the shell
• Use test to validate the existence of directories and files as well as to compare numeric and string values
• tr changes characters typed at keyboard
• sed reads a file as its input and outputs the file’s modified contents
• Shell functions can make programmer more efficient
A Guide to Unix Using Linux, Fourth Edition 32
Command Summary
A Guide to Unix Using Linux, Fourth Edition 33
Command Summary (continued)