Unix Oracle Shell Script PDF
Unix Oracle Shell Script PDF
IN AN ORACLE ENVIRONMENT
By
William A. Ducat
Ambassador, Inc.
5299 DTC Boulevard
Suite 290
Englewood, CO 80112
(888) 775-3778 x227 (Voice)
(630) 839-5264 (Fax)
Table of Contents
Introduction................................................................................................................................................. 3
Conventions ............................................................................................................................................ 3
Building Blocks .......................................................................................................................................... 4
Concepts.................................................................................................................................................. 4
STDOUT............................................................................................................................................. 4
STDERR ............................................................................................................................................. 4
STDIN ................................................................................................................................................. 5
Environment Variables ....................................................................................................................... 6
Scripts.................................................................................................................................................. 6
Parameter Passing ............................................................................................................................... 8
Flow Control ....................................................................................................................................... 9
Identifying your process.................................................................................................................... 10
Practical Examples .................................................................................................................................... 11
Password Management ......................................................................................................................... 11
Embedded SQL..................................................................................................................................... 12
Embedded Subroutines (aka Functions) ............................................................................................... 13
Passing Parameters................................................................................................................................ 15
Global Functions ................................................................................................................................... 18
Conclusion ................................................................................................................................................ 22
Sample Code
Figure 1 - Redirecting STDERR to a file.................................................................................................... 4
Figure 2 - Redirecting STDERR to STDOUT............................................................................................ 4
Figure 3 - Redirecting STDIN in a script.................................................................................................... 5
Figure 4 - Basic script ................................................................................................................................. 7
Figure 5 – Sample setup_passwords.ksh script......................................................................................... 11
Figure 6 - PS results on HP or Sun ........................................................................................................... 12
Figure 7 - PS results on Compaq or Linux ............................................................................................... 12
Figure 8 - Embedding SQL in a KSH script ............................................................................................. 13
Figure 9 - Implementing a user-defined function in a KSH script ........................................................... 14
Introduction
The primary purpose of this paper is to provide a starting point for your own scripting projects. To accomplish this, the paper
is divided into two major sections. The “Building Blocks” section will describe some of the required basic concepts, and the
“Practical Examples” section takes these basic constructs and steps through the construction of a rather useful script. The
script starts out as a very basic script, and by applying multiple new features, becomes a very flexible and useful tool.
Developing scripts for the Oracle environment involves performing some rather complex tasks, and the KORN shell naturally
lends itself to the task. Because of this, and its wide availability, we will use the KORN shell for all examples.
In the UNIX environment, a users interactive environment or scripts always run in some sort of shell. A shell can be thought
of as an interface to the underlying UNIX command set. Most tasks can be completed in any available shell, but each shell
has various attributes, which tend to make it desirable for various applications. For instance, the Bourne shell (/bin/sh) is a
very basic shell, which is common to most UNIX installations. Many install programs use the BOURNE shell since one
script can be used, unchanged, on multiple platforms. The C shell (/bin/csh) has various features to assist in the interactive
environment, and many users make the C shell their default 1 shell for this reason. The KORN shell (/bin/ksh) lends its self to
heavy scripting, and includes the ability to define functions that are local to a script, as well as functions that are available to
the users interactive session. Another relative newcomer in the shell arena is the BASH shell (/bin/bash)(a.k.a Bourne Again
Shell). BASH attempts to combine the best of the C and BOURNE shells into one. BASH is not widely used at this time, but
has the potential to become very popular.
Conventions
In this paper when a space is critical, the β symb ol will be used to denote each space.
1
The default shell for a user is specified on the users entry in the /etc/passwd file.
Building Blocks
UNIX can be thought of as a very thin operating system. Instead of providing a series of very powerful commands with
numerous options, such as the VMS operating system, it provides a large number of very simple commands which can be
strung together to obtain the desired result. A simple script is nothing more than a series of commands or strings of
commands executed in a sequential manner. A complex script uses flow control constructs and conditional operators to
control the execution of commands much like a 3GL such as “C”, BASIC or Fortran.
Concepts
Numerous texts cover the syntax and purpose of all of the UNIX commands, and we will not attempt to cover all of them
here. We will however cover some of the more useful ones from a scripting standpoint, as well as some basic issues related to
all commands.
There are three things common to most commands. First, they need a source of input. Second, they need somewhere to send
their output. Third, they need somewhere to send the results of any errors encountered. In the UNIX world, we have
“standard input” (STDIN), “standard output” (STDOUT), and “standard error” (STDERR). The default values for each
command differ, but as a rule, STDOUT and STDERR are sent to the screen, and STDIN will be requested interactively from
the user, or from a file.
STDOUT
When performing a command such as “ls”, the results of the listing are displayed to the screen. This can be changed by
redirecting STDOUT with the “>” redirector. For instance, if the “ls >listing.out” command is issued, the file “listing.out”
will be created if it does not exist, or it will be replaced if it does exist. When complete, the file will contain the results of the
”ls” command. When the “>” is used, the results will not be shown on the screen. The “>>” redirector works like “>” except
it will append the to a file if it already exists.
STDERR
If an “ls” command returns “no files found”, the resulting error message is shown on the screen. If the same command is
performed except the results are redirected to a file, the resulting file will be empty and the error message will still be
displayed on the screen. The reason is that the results are being sent to STDOUT, and the error is sent to STDERR. Take the
following command as an example:
STDIN
Standard input typically comes from one of three sources. The first is interactively from the keyboard, the second is from an
input file, and the third is from the output of another command. When writing a script to be run in batch mode, keyboard
entry is usually not an option. For instance, if a script is require to enter Sql*Plus and execute an update statement, how can it
be done? One possibility would be to add an “@” command to the startup of Sql*Plus, but maybe a single file is desired.
One answer is to have Sql*Plus take it’s input from the script instead of the keyboard. Redirecting STDIN can do this.
The second method of changing standard input is to pipe “|” the results of one command into another command. For instance,
the sort command will take a file name as input and display the sorted results to the screen, but other methods are possible.
The following two commands accomplish the same results:
sort myfile
cat myfile | sort
In the first example, sort takes “myfile” as the input, but in the second example, the results of the cat command (which
simply displays a file) are sent as input to the sort command. While the second example may seem more complicated, it
opens up a whole world of possibilities. For instance, let’s assume we have a file containing the results of a series of Oracle
queries, and we want to display a sorted list of “ORA” errors contained in the file. In addition, we want to align the output so
each “ORA-“ string is indented in a manner that places the “O” in column 4. The following command would do this:
Let’s take this command apart. The first portion is the grep. Oracle errors generally start with “ORA-“, and we use grep to
extract all of these lines from “myfile”. When Oracle generates the error messages, the resulting lines can be indented all over
the place. We want them to be consistent for display purposes. The sed command is used to take the results of the grep
command and format them. Sed is a stream editor, which applies VI like commands to each line of input. In our case, we are
going to apply two substitute commands (separated by the “;” character) to each line. The first substitution, (s/^β*//),
will find the beginning of line followed by any number of spaces, and remove the spaces. This will result in all the ORA-
lines being left justified. The second substitution will add 3 spaces to the beginning of each line. Next, the results are sent to
sort where they are displayed on the screen in sorted order. Of course, we could pipe the results to a file using the “>”
redirector, or the results could be displayed to the screen and sent to a file by piping the results to the “tee” command. The
options are really only bound by your imagination. In fact, UNIX commands can be thought of much like a box of
“Tinkertoys”. They can be put them together in many ways to solve the same problem, and there is no one correct answer.
The best we can hope to accomplish here is to show various contraptions others have built, and turn your imagination loose to
invent your own!
Environment Variables
Environment variables behave much like variables in any language except they are available throughout the shell
environment. There are two basic ways to view the contents of an environment variable. First, the UNIX command “env”
will show all variables, and the echo command can be used to display a single variable. When referencing an individual
variable, the variable name must be referenced starting with the “$” character, and optionally, the variable name can be
enclosed in “{}” characters. For instance, to display the contents of the ORACLE_SID variable, either of the following
commands could be used:
echo $ORACLE_SID
echo ${ORACLE_SID}
While both commands will work, the second method is desirable. The basic reason is consistency. Good programming
techniques dictate a consistent style, and the first method does not always work. For instance, let’s assume a script must
display the contents of the ORACLE_SID variable followed by “_world”.
echo $ORACLE_SID_world
echo ${OACLE_SID}_world
The second example would give the desired result, but the first would be looking for a variable named ORACLE_SID_world.
NOTE: Keep in mind that variable names, like most things in UNIX, are case sensitive.
One use of environment variables is to store username and password combinations. Consider the following:
SYSTEM_CONNECT=system/manager
sqlplus ${SYSTEM_CONNECT}
In this example, sqlplus uses the contents of the SYSTEM_CONNECT variable as the username and password. The
Password Management section goes into this in more detail.
Scripts
If a series of commands are placed in a file, it is called a script. To run a script, first modify the permissions on the file to
include execute permission, and then enter its name at the command line. For instance, consider the following script called
s1.ksh:
date
pwd
whoami
If this script were created using your favorite editor (which should be vi J), execute permission could be granted via the
following command:
chmod +x s1.ksh
Assuming the current path contains “.”, simply typing “s1.ksh” would execute the script. If “.” Is not in the path, the script
could be executed by entering “./s1.ksh”. A run of this script might look something like:
%s1.ksh
Sat Dec 2 13:59:28 MST 2000
/common/bin
wducat
%
This is scripting at its most basic, and the remainder of this paper will focus on writing scripts that are more powerful.
Throughout this paper, many scripts start with “#! /bin/ksh”. Even though it looks like a comment, it is not. By including this
line, UNIX will use Korn shell syntax rules regardless of the default shell.
Parameter Passing
Many scripts require parameters to be passed in to assist in processing. When calling a script from the UNIX command line,
parameters can be included by simply including them on the same line as the command, separating then with spaces. If a
parameter must contain spaces, simply enclose the parameter in double quotes.
Once in side a KSH script, there are a few ways to obtain parameter information. The following is a list of built in variables
that can be used:
Variable Alternate Usage
$# ${#} The number of parameters passed in
$0 ${0} The basic command without any parameters
$1 ${1} The first parameter passed in
$2 ${2} The second parameter passed in
.
.
.
#! /bin/ksh
echo $1
echo $2
echo $3
echo $#
echo $0
echo Done
Reading the output, the first parameter is “this”, the second is “is a”, and the third is “test”. Three parameters were sent, and
the command s2.ksh was run from the current directory.
Flow Control
One of the basic requirements of any language is that it provides the ability to control the flow of execution. Functions
provide the ability to jump to another section of code, but what if code needs to be skipped? The Korn shell provides four
basic constructs used in many scripts. In this paper, we use two of them. They are “If” and “for”. A brief overview of these
constructs follows:
IF PROCESSING
The “if” command provides the ability to perform some task based on some expression. Frequently the expression involves
comparing two numbers or two strings. The operators used to compare strings are “=” (equal to) and “!=” (not equal to).
Numbers are compared using the “-gt” (greater than), “-ge” (greater than or equal to), “-eq” (equal to), “-ne” (not equal), “-
le” (less than or equal to), and “-lt” (less than). When performing numeric comparisons, the optional “test” syntax should be
used. The following code is a sample of this:
x=5
if [ test ${x} –gt 0 ] ;then
echo ${x} is greater than 0
else
echo ${x} is not greater than 0
fi
Please see a good Korn shell syntax text for more details on using the “if” constructs.
FOR PROCESSING
The “for loop” is very useful for processing a list of values. Consider the following example:
for x in a b c ;do
echo ${x}
done
This code will print out a, b, and c, each on their own line. The real power of the “for loop” comes in the definition of the list.
The list can be a command that generates multiple lines of output. When this is the case, the loop variable takes on each line
of output for the duration of the loop. Consider the following example:
This loop would call “my_function” once for each file in the directory, passing the file name as a parameter.
Practical Examples
This section of the paper will use the basic concepts already discussed to build tools that are useful in an Oracle environment.
Password Management
One of the classic problems in scripting involves password management. Typically, passwords end up getting hard coded,
and this poses both security and logistical problems. From a security standpoint, every script, which contains a hard coded
password, must be protected so only authorized persons can view the scripts. From a logistical standpoint, when passwords
are changed, every script needs to be found and modified. One other logistical issue comes up whenever help is needed to
debug a script. In this case, only those with the passwords can help. Yet another comes up whenever a script is being worked
on, anyone looking over your shoulder can see passwords! By using environment variables, these problems can be avoided.
One workable solution is the creation of a script, which sets environment variables for each password. A sample of this
script, which we will call “setup_passwords.ksh”, follows:
SYSTEM_CONNECT=system/manager
SYS_CONNECT=sys/change_on_install
Since the “other” group cannot see the file, the passwords are now secure from everyone except the root account, or other
users who have your password, but that is a personal problem!
Once we create this file, it can be used many ways. First, if it is called from your “.profile”2 , the variables are available at the
command line. Second, if it is run at the beginning of each script, the variables are available within the script, and others can
look at the scripts without being able to see the passwords. When calling the script, always proceed the call with a dot and a
space so variables are visible to the script. For instance, assuming the file is located in the /common/bin directory, the
following could be added to each script:
.β/common/bin/setup_passwords.ksh
If this is done in the .profile, aliases could be created to log into Oracle. A sample alias follows:
From that point on, typing “sqlplusS” would start sqlplus as the system account for the default instance.
*** WARNING ***
2
The “.profile” file is automatically run when a new KSH session is started.
There is one very large warning here, depending on the version of UNIX being used. If a parameter password is passed to a
UNIX application, and perform a “ps –aef” in another window, all of the parameters passed in the first session may be
shown. This includes passwords! Sqlplus is simply a UNIX application, and is subject to the same issues. Oracle has seen fit
to fix this problem in some, but not all UNIX environments. For instance, if “sqlplus system/manager” were typed at the
UNIX prompt on a Sun or HP system, the following could be seen in another window:
Embedded SQL
By redirecting STDIN, SQL or PL/SQL code can be directly coded into a KORN shell script. The main advantage of this
technique is that UNIX environment variables can be referenced within the SQL portion of the script as well as the shell area.
Consider the following example:
#! /bin/ksh
. /common/bin/setup_passwords.ksh
v\$license,global_name ;
quit;
!!
%l1.ksh
Connected.
Notice the first line of the output is a line containing “Connected.” This line is the result of the “connect” statement and, as of
this time, there is no way to get sqlplus to stop producing that output. Never fear, the Embedded Subroutines section
discusses sways of dealing with this issue.
#! /bin/ksh
. /common/bin/setup_passwords.ksh
__show_licenses()
{
$ORACLE_HOME/bin/sqlplus -s /nolog <<!!
set line 200
set feedback off
connect ${SYSTEM_CONNECT};
column global_name heading "Instance" format a15
column sessions_max heading "Max" format 9999
column sessions_warning heading "Warning" format 9999
column sessions_current heading "Current" format 9999
column sessions_highwater heading "Highwater" format 9999
select
global_name,sessions_max,sessions_warning,
sessions_current-1 sessions_current,
sessions_highwater
from
v\$license,global_name ;
quit;
!!
}
__show_licenses
__show_licenses >scrap.out
In this case, nothing would be sent to the screen, but the file scrap.out would contain the output. This still does not get rid of
the “Connected.” line discussed earlier, but this can be accomplished by piping the results through grep to eliminate the
offending output. The following would accomplish this:
This grep command would eliminate any lines containing only the string “Connected.” so the results would look like:
%l3.ksh
One interesting thing to note is the existence of the backslash character prior to the period character. The grep command uses
regular expression matching, and the period represents “any one character”. The backslash character indicates that the
following “special character” should be interpreted literally, not as a part of a regular expression. If the backslash were
removed, the code would eliminate lines containing things such as “ConnectedX”, “Connectedβ”, etc. If this is what is
desired, then the period character can be used, but if the desire is to specifically match the period character, the backslash is
required. This example would work with or without the backslash, but if sloppy style is used, the issue may be missed in later
code, resulting in some very hard to debug issues. In short, mean what you say, and code what you mean. There is no “do as I
mean, not what I say” mode in UNIX, yet.
Passing Parameters
Up until now, the script we have been building only works against the default instance3 . By using parameters, we can
increase the usefulness of the script. Before writing this script, there are a few issues to be considered. Parameters passed into
functions are handled the same way as parameters passed into scripts (as discussed in the Parameter Passing section), and
variables passed to the script must be passed to the function if they are to be used by the function. Consider the following
example:
#! /bin/ksh
__doit()
{
echo ${1} ${2}
}
echo ${1} ${2}
__doit test ${1}
The two parameters on the second to the last line will refer to the parameters passed in at the command line, and the echo
command inside the __doit function will refer to the parameters passed in on the last line. The following run illustrates this:
In this case, the first parameter passed into the script contains “aaa”, and that value is passed as the second parameter to the
__doit function.
Getting back to our main script, if we modify it to expect a SID as the first parameter, then we no longer need to set our
default instance prior to running the script. The following shows this. Notice the parameter references on the connect line as
well as on the call to __show_licenses.
#! /bin/ksh
. /common/bin/setup_passwords.ksh
__show_licenses()
{
$ORACLE_HOME/bin/sqlplus -s /nolog <<!!
set line 200
set feedback off
connect ${SYSTEM_CONNECT}@${1};
column global_name heading "Instance" format a15
column sessions_max heading "Max" format 9999
column sessions_warning heading "Warning" format 9999
column sessions_current heading "Current" format 9999
column sessions_highwater heading "Highwater" format 9999
select
global_name,sessions_max,sessions_warning,
sessions_current-1 sessions_current,
sessions_highwater
from
v\$license,global_name ;
3
The default instance is the one used if no SID is passed on a connect string
quit;
!!
}
One interesting note is that if a parameter is not passed in, it ends up connecting as system/manager@. This results in a
connection to the default instance. If this is not desired, a few lines of conditional logic could be added to the bottom in order
to verify that a parameter was sent. The following script demonstrate:
#! /bin/ksh
. /common/bin/setup_passwords.ksh
__show_licenses()
{
$ORACLE_HOME/bin/sqlplus -s /nolog <<!!
set line 200
set feedback off
connect ${SYSTEM_CONNECT}@${1};
column global_name heading "Instance" format a15
column sessions_max heading "Max" format 9999
column sessions_warning heading "Warning" format 9999
column sessions_current heading "Current" format 9999
column sessions_highwater heading "Highwater" format 9999
select
global_name,sessions_max,sessions_warning,
sessions_current-1 sessions_current,
sessions_highwater
from
v\$license,global_name ;
quit;
!!
}
if [ $# -ne 1 ] ;then
__show_licenses ${1}| grep –v “^Connected\.$”
else
echo “ERROR: Invalid number of parameters specified”
echo “ One instance name must be specified.”
fi
If we did not want to pass in the names of our instances, we could hard code them. Consider the following example:
#! /bin/ksh
. /common/bin/setup_passwords.ksh
__show_licenses()
{
$ORACLE_HOME/bin/sqlplus -s /nolog <<!!
set line 200
set feedback off
connect ${SYSTEM_CONNECT}@${1};
%l6.ksh
While it works, the results are not pretty. A few more modifications could correct the formatting issues:
#! /bin/ksh
. /common/bin/setup_passwords.ksh
__show_licenses()
{
$ORACLE_HOME/bin/sqlplus -s /nolog <<!!
heading=on
__show_licenses prod|grep -vE "^Connected\.$|^$"
heading=off
__show_licenses devel|grep -vE "^Connected\.$|^$"
__show_licenses systest|grep -vE "^Connected\.$|^$"
In this case, a few changes were made. First, We added a “heading” environment variable and set it so only the first run
would cause the heading to be printed by sqlplus. Notice the “set heading” command now references the “heading” variable
which is set “on” or “off” in the shell area. Next, we added the -E options to the grep so we could also exclude blank lines.
The “^$” pattern matches any line containing only the beginning of the line immediately followed by the end of the line. The
results of this code can be seen below:
This works well, but it is still hard coded. Every time an instance is added to the environment, the code must change. This
can be fixed via the creation of a global function as describes in the Global Functions section.
Global Functions
There are times when it is helpful to have a small piece of code that can be called from multiple scripts. In the previous
example, we need to dynamically generate a list of instances on the machine we are running on. This code could be added to
the script, but it is something which could be useful in multiple areas. If the code was copied to each script, maintenance
would be a problem if the logic ever changed. For instance, the first version may only work on the local machine, but if
another machine was added, the code could be modified to pick up those instances as well. If the code is in one place, then
one change would in effect, modify all scripts.
Our first task is to create the logic required to generate a list of instances on the local machine. For our purposes, we will
assume the tnsnames.ora file or the Oracle Names server is configured in a manner where the instance can be reached by
including an @ after the password on a connect string. For instance, system/manager@devel will connect to the instance with
a SID of devel. Most installations that I have been involved in use this standard, but there are reasons that this standard may
not be used. If the SID and connect information are different, appropriate changes will need to be made to the sample scripts.
Every instance running on a machine creates what is known as a PMON process. Using the UNIX “ps” command, we can
take a look at these processes. Consider the following series of commands:
The first command shows us all of the Oracle pmon processes as well as our grep! The second command filters out the grep.
In the third command, we modify the second grep to remove the sed command also added to the third command. The sed
command tells the system to replace everything from the beginning of the line through the ora_pmon_ with nothing. The
result is a list of all of the currently running instances.
The following script creates a function using the above logic to create an environment variable containing a list of all
available instances. Line numbers are included for reference purposes.
1 #! /bin/ksh
2
3 gen_sid_list()
4 {
5
6 sid_list=""
7 touch /tmp/sids_$$.out
8 ps -aef | \
9 grep ora_pmon | \
10 grep -vE 'sed|grep'| \
11 sed -e "s/^.*ora_pmon_//" \
12 >/tmp/sids_$$.out
13
14 for iName in `sort /tmp/sids_$$.out` ;do
15 tnsping ${iName} >/tmp/ping_$$.out
The first thing done is the creation of a function called gen_sid_list. The placement of this function will be discussed later.
The following is an analysis of the various lines in the function:
Line
Number Purpose
6 Creates an empty environment variable which will ultimately contain the list of
instances
8 Issues the same ps command discussed above, except the results are sent to a
temporary file
14 Sets up a for loop which takes the sorted list of instance names in the temp file, and
processes t hem one at a time, setting the variable
15 Performs a tnsping on each instance to very if it is available. The results of the ping
are sent to a temp file for further review
16 Counts the number of TNS errors returned from the ping
17 Determines if the instance should be added to the variable
18 Adds the instance to the variable
20 Displays an error if problems were found connecting to the instance
22 Cleans up temporary file
24 Cleans up temporary file
If the above script is placed in another file of functions, the script can be called from multiple scripts as long as the file of
functions is called from each script. In our example, the function was placed in a file called functions.ksh.
The following script as modified from the example in the Passing Parameters section uses this new function:
#! /bin/ksh
. /common/bin/setup_passwords.ksh
. /common/bin/functions.ksh
__show_licenses()
{
$ORACLE_HOME/bin/sqlplus -s /nolog <<!!
set line 200
set feedback off
set heading ${heading}
connect ${SYSTEM_CONNECT}@${1};
column global_name heading "Instance" format a15
column sessions_max heading "Max" format 9999
column sessions_warning heading "Warning" format 9999
column sessions_current heading "Current" format 9999
column sessions_highwater heading "Highwater" format 9999
select
global_name,sessions_max,sessions_warning,
sessions_current-1 sessions_current,
sessions_highwater
from
v\$license,global_name ;
quit;
!!
}
gen_sid_list
heading=on
for iName in $sid_list ;do
__show_licenses ${iName}|grep -vE "^Connected\.$|^$"
heading=off
done
Notice the addition of a call to functions.ksh at the top. This makes the gen_sid_list function available. Nothing has changed
in the __show_licenses function. First, we call gen_sid_list to setup the sid_list environment variable. The heading variable is
then set to “on” for the first run. Next a “for loop” is setup to loop through the list of instances. Each time through the loop,
the iName variable will contain the name of the next Oracle instance to process. Next, the __show_licenses function is called,
and the instance is specified via the iName variable that is passed in as a parameter. Finally, the heading variable is set to
“off” for the remaining instances. This loop will be executed repeatedly for each instance.
This code is now very generic. If a new instance is brought up on the machine, this script will automatically find it. If an
existing instance is taken off-line, it will no longer show up.
Conclusion
The process we just went through only scratches the surface of what can be accomplished with a well-written script. Under
close inspection, a number of shortcomings become obvious in the above example. For instance, what if the Oracle instances
are on multiple machines and we want to see them all together? What if the instance names do not match the connect strings?
What happens if gen_sid_list generates an error? Can we get the script to stop in this case? As any programmer knows once a
program is “finished”, the real work often begins as enhancements are implemented. Scripting in Korn shell is very much like
programming in any 3GL such as “C”. If the task is approached from a programmer’s point of view, the possibilities are
endless.