P. 1
Unix Shell Scripting - In an Oracle Environment

Unix Shell Scripting - In an Oracle Environment

|Views: 99|Likes:
Published by kuldeep_kumar_12

More info:

Published by: kuldeep_kumar_12 on Mar 28, 2012
Copyright:Attribution Non-commercial

Availability:

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

03/28/2012

pdf

text

original

UNIX SHELL SCRIPTING 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)

www.rmoug.org

RMOUG Training Days 2001

UNIX Shell Scripting for Oracle

Ducat

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

www.rmoug.org

RMOUG Training Days 2001

Many install programs use the BOURNE shell since one script can be used. BASH is not widely used at this time. The “Building Blocks” section will describe some of the required basic concepts. we will use the KORN shell for all examples. The script starts out as a very basic script.k. When something is enclosed in a box. it contains commands to enter. as well as functions that are available to the users interactive session. but has the potential to become very popular. Most tasks can be completed in any available shell. To accomplish this. www. and the “Practical Examples” section takes these basic constructs and steps through the construction of a rather useful script. and its wide availability. Because of this. as is this paragraph. and includes the ability to define functions that are local to a script. a users interactive environment or scripts always run in some sort of shell. the paper is divided into two major sections. In the UNIX environment. the Bourne shell (/bin/sh) is a very basic shell. which tend to make it desirable for various applications.org RMOUG Training Days 2001 . the text of a UNIX script. but each shell has various attributes. the b symb ol will be used to denote each space. BASH attempts to combine the best of the C and BOURNE shells into one. For instance. Developing scripts for the Oracle environment involves performing some rather complex tasks. Another relative newcomer in the shell arena is the BASH shell (/bin/bash)(a.a Bourne Again Shell). The KORN shell (/bin/ksh) lends its self to heavy scripting. and by applying multiple new features. or the results of a script or command. becomes a very flexible and useful tool.UNIX Shell Scripting for Oracle Ducat Introduction The primary purpose of this paper is to provide a starting point for your own scripting projects. 1 The default shell for a user is specified on the users entry in the /etc/passwd file. on multiple platforms. Conventions In this paper when a space is critical. A shell can be thought of as an interface to the underlying UNIX command set. and many users make the C shell their default 1 shell for this reason.rmoug. which is common to most UNIX installations. unchanged. and the KORN shell naturally lends itself to the task. The C shell (/bin/csh) has various features to assist in the interactive environment.

they need somewhere to send the results of any errors encountered. the results. such as the VMS operating system. www. If the same command is performed except the results are redirected to a file. Third. we have “standard input” (STDIN). A simple script is nothing more than a series of commands or strings of commands executed in a sequential manner. “standard output” (STDOUT). results are sent to the results.txt 2>&1 Figure 2 . For instance. Take the following command as an example: ls myfile* >results. they need somewhere to send their output.rmoug.txt file. BASIC or Fortran. Concepts Numerous texts cover the syntax and purpose of all of the UNIX commands.Redirecting STDERR to a file STDERR is referenced via the “2>” redirector. Consider the following command: ls myfile* >results. In the UNIX world. The “>>” redirector works like “>” except it will append the to a file if it already exists. The reason is that the results are being sent to STDOUT. or it will be replaced if it does exist. We will however cover some of the more useful ones from a scripting standpoint. This can be changed by redirecting STDOUT with the “>” redirector. as well as some basic issues related to all commands. A complex script uses flow control constructs and conditional operators to control the execution of commands much like a 3GL such as “C”.txt 2>errors. STDOUT can be referenced as &1. When complete. the file “listing. STDOUT When performing a command such as “ls”. and errors are sent to the errors. or from a file. The default values for each command differ. but as a rule.out” will be created if it does not exist.txt Figure 1 . In a given command. Instead of providing a series of very powerful commands with numerous options. Second. it provides a large number of very simple commands which can be strung together to obtain the desired result. if the “ls >listing. STDOUT and STDERR are sent to the screen. the resulting error message is shown on the screen. There are three things common to most commands. the resulting file will be empty and the error message will still be displayed on the screen.Redirecting STDERR to STDOUT In this case. and the error is sent to STDERR. First. the results will not be shown on the screen. and “standard error” (STDERR). the file will contain the results of the ”ls” command. they need a source of input.out” command is issued.txt file. since STDERR is redirected to STDOUT. In this case.UNIX Shell Scripting for Oracle Ducat Building Blocks UNIX can be thought of as a very thin operating system.txt file will contain both the results and the errors (if any). When the “>” is used. the results of the listing are displayed to the screen. and we will not attempt to cover all of them here. and STDIN will be requested interactively from the user.org RMOUG Training Days 2001 . STDERR If an “ls” command returns “no files found”.

and we want to display a sorted list of “ORA” errors contained in the file. For instance. sqlplus scott/tiger –s <<!! select * from global_name. For instance. or the results could be displayed to the screen and sent to a file by piping the results to the “tee” command. For instance.” character) to each line. The following command would do this: grep “ORA-“ myfile | sed –e ‘s/^b*//. it opens up a whole world of possibilities. but in the second example. Of course. Next. but maybe a single file is desired. In addition. When writing a script to be run in batch mode. quit. When this happens. sort takes “myfile” as the input. and remove the spaces. We want them to be consistent for display purposes.org RMOUG Training Days 2001 . and the third is from the output of another command. The first is interactively from the keyboard. The first set of bracketing characters must immediately follow the “<<” redirector. but other methods are possible. In our case.rmoug. the sort command will take a file name as input and display the sorted results to the screen. “!!” is used to bracket the starting and ending of the input.Redirecting STDIN in a script In this example. and we use grep to extract all of these lines from “myfile”. the redirection does not happen properly. Oracle errors generally start with “ORA-“. (s/^b*//). The second substitution will add 3 spaces to the beginning of each line.s/^/bbb/’ | sort Let’s take this command apart. will find the beginning of line followed by any number of spaces. let’s assume we have a file containing the results of a series of Oracle queries. The most common problem when coding these brackets occurs when spaces are entered before or after the bracketing characters. the resulting lines can be indented all over the place. One answer is to have Sql*Plus take it’s input from the script instead of the keyboard. This will result in all the ORAlines being left justified. we are going to apply two substitute commands (separated by the “. keyboard entry is usually not an option. The options are really only bound by your imagination. There is nothing special about the “!!” characters.$s/ *$// The second method of changing standard input is to pipe “|” the results of one command into another command. the results are sent to sort where they are displayed on the screen in sorted order. the “<<” redirector indicates that an alternate STDIN follows. In this case. we could pipe the results to a file using the “>” redirector. which applies VI like commands to each line of input.UNIX Shell Scripting for Oracle Ducat STDIN Standard input typically comes from one of three sources. !! Figure 3 . how can it be done? One possibility would be to add an “@” command to the startup of Sql*Plus. and nothing can follow the characters on the line. UNIX commands can be thought of much like a box of www. The first substitution. and the results can be very confusing. While the second example may seem more complicated. Redirecting STDIN can do this. if a script is require to enter Sql*Plus and execute an update statement. The following two commands accomplish the same results: sort myfile cat myfile | sort In the first example. The first portion is the grep. the characters must exist on a line all by themselves. the results of the cat command (which simply displays a file) are sent as input to the sort command. In fact. ! vi hint I have never found a reason to end lines with spaces in a script. we want to align the output so each “ORA-“ string is indented in a manner that places the “O” in column 4. To end the standard input. Sed is a stream editor. The sed command is used to take the results of the grep command and format them. and any bracketing characters can be used as long as they follow the following rules. and the following command can be used to remove all trailing spaces from a file when using vi: :1. When Oracle generates the error messages. the second is from an input file.

There are two basic ways to view the contents of an environment variable. first modify the permissions on the file to include execute permission. sqlplus uses the contents of the SYSTEM_CONNECT variable as the username and password. to display the contents of the ORACLE_SID variable. One use of environment variables is to store username and password combinations.org RMOUG Training Days 2001 . but not exporting password variables is the safest option. echo $ORACLE_SID_world echo ${OACLE_SID}_world The second example would give the desired result. and there is no one correct answer. it does pose a security problem. but a great deal of care must be taken when using this command.UNIX Shell Scripting for Oracle Ducat “Tinkertoys”. are case sensitive. For instance. To run a script.rmoug.ksh: date pwd whoami www. EXPORTING ENVIRONMENT VARIABLES The scope of environment variables can be expanded using the “export” command. When referencing an individual variable. the UNIX command “env” will show all variables. this command can be used to display those values. There are possible workarounds to this. They can be put them together in many ways to solve the same problem. the variable name must be referenced starting with the “$” character. NOTE: Keep in mind that variable names. and then enter its name at the command line. Scripts If a series of commands are placed in a file. it is called a script. The basic reason is consistency. When a variable is exported. and the first method does not always work. either of the following commands could be used: echo $ORACLE_SID echo ${ORACLE_SID} While both commands will work. The Password Management section goes into this in more detail. For instance. and the echo command can be used to display a single variable. let’s assume a script must display the contents of the ORACLE_SID variable followed by “_world”. consider the following script called s1. like most things in UNIX. the variable name can be enclosed in “{}” characters. For instance. 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. and optionally. First. but the first would be looking for a variable named ORACLE_SID_world. If a variable that contains a password is exported. the second method is desirable. Consider the following: SYSTEM_CONNECT=system/manager sqlplus ${SYSTEM_CONNECT} In this example. The “ps aew” command will show all of the exported environment variables for all other processes on the system. that variable is viable to other scripts called from the process where the export was performed. The best we can hope to accomplish here is to show various contraptions others have built. While this can be very useful. Good programming techniques dictate a consistent style.

rmoug.org RMOUG Training Days 2001 .UNIX Shell Scripting for Oracle Ducat Figure 4 .Basic script www.

and the remainder of this paper will focus on writing scripts that are more powerful. Once in side a KSH script. execute permission could be granted via the following command: chmod +x s1. simply enclose the parameter in double quotes. If “.” Is not in the path. If a parameter must contain spaces. it is not. UNIX will use Korn shell syntax rules regardless of the default shell./s1. simply typing “s1.”.rmoug. . separating then with spaces. Consider the following example: #! /bin/ksh echo $1 echo $2 echo $3 echo $# echo $0 echo Done Alternate ${#} ${0} ${1} ${2} Usage The number of parameters passed in The basic command without any parameters The first parameter passed in The second parameter passed in The following is a sample run of this script: www.ksh Sat Dec 2 13:59:28 MST 2000 /common/bin wducat % This is scripting at its most basic.ksh Assuming the current path contains “. Even though it looks like a comment. .ksh”. the script could be executed by entering “. The following is a list of built in variables that can be used: Variable $# $0 $1 $2 . many scripts start with “#! /bin/ksh”. By including this line. there are a few ways to obtain parameter information. When calling a script from the UNIX command line.org RMOUG Training Days 2001 .ksh” would execute the script. parameters can be included by simply including them on the same line as the command.UNIX Shell Scripting for Oracle Ducat If this script were created using your favorite editor (which should be vi ☺). A run of this script might look something like: %s1. Throughout this paper. Parameter Passing Many scripts require parameters to be passed in to assist in processing.

the second is “is a”. A brief overview of these constructs follows: IF PROCESSING The “if” command provides the ability to perform some task based on some expression. and “-lt” (less than)./s2. “-ge” (greater than or equal to). the first parameter is “this”.ksh was run from the current directory. 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.ksh this “is a” test this is a test 3 .ksh Done % Reading the output. “-ne” (not equal). we use two of them.rmoug. Numbers are compared using the “-gt” (greater than).UNIX Shell Scripting for Oracle Ducat % s2. “-eq” (equal to). The following code is a sample of this: x=5 if [ test ${x} –gt 0 ] . FOR PROCESSING The “for loop” is very useful for processing a list of values. Consider the following example: for x in a b c . They are “If” and “for”. and the command s2. the optional “test” syntax should be used.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. and the third is “test”. When performing numeric comparisons. The operators used to compare strings are “=” (equal to) and “!=” (not equal to).do echo ${x} done www.org RMOUG Training Days 2001 . In this paper. Frequently the expression involves comparing two numbers or two strings. “­ le” (less than or equal to). Three parameters were sent. Flow Control One of the basic requirements of any language is that it provides the ability to control the flow of execution.

the file scrap12345. If the PID is 12345 and the command: “ls >/tmp/scrap$$. Consider the following example: for x in `ls` .a your PID). and c. b. each on their own line.do my_function ${x} done This loop would call “my_function” once for each file in the directory. this is a very good technique for isolating results. When this is the case.org RMOUG Training Days 2001 . passing the file name as a parameter. then remove the file when the task is completed. The list can be a command that generates multiple lines of output.k. If a script can be run from multiple windows simu ltaneously. Identifying your process Many times a script will need to write out a temporary file.out” is issued. For instance. typing “echo $$” at the UNIX prompt will return the current process ID (a. The real power of the “for loop” comes in the definition of the list. One technique used when specifying a temporary file name is to append the current process id to the name of the file. the loop variable takes on each line of output for the duration of the loop. The current process id can be obtained via the “$$” variable.UNIX Shell Scripting for Oracle Ducat This code will print out a. www.out will be created in the /tmp directory.rmoug.

Second.UNIX Shell Scripting for Oracle Ducat Practical Examples This section of the paper will use the basic concepts already discussed to build tools that are useful in an Oracle environment.ksh script If this script is run at the start of each script. if it is called from your “. which sets environment variables for each password. with the group set to “dba”. follows: SYSTEM_CONNECT=system/manager SYS_CONNECT=sys/change_on_install Figure 5 – Sample setup_passwords. and others can look at the scripts without being able to see the passwords. A sample of this script. the variables are available at the command line. aliases could be created to log into Oracle. every script needs to be found and modified. the variables are available within the script.org RMOUG Training Days 2001 . Password Management One of the classic problems in scripting involves password management. it can be used many ways. For instance.rmoug. *** WARNING *** 2 The “. A sample alias follows: alias sqlplusS=’sqlplus ${SYSTEM_CONNECT}’ From that point on.ksh Since the “other” group cannot see the file. or other users who have your password. every script.profile”2 . passwords end up getting hard coded.profile” file is automatically run when a new KSH session is started. but that is a personal problem! Once we create this file. Yet another comes up whenever a script is being worked on. only those with the passwords can help. When this is done. then the file can be owned by the “oracle” account. the passwords are now secure from everyone except the root account. when passwords are changed.b/common/bin/setup_passwords. The chmod command should be used to set the privileges to “770”. these problems can be avoided. anyone looking over your shoulder can see passwords! By using environment variables. the following could be added to each script: . assuming the file is located in the /common/bin directory. if only members of the UNIX dba group should have password access. and privileges should be set so only members of the group should be able to read the file. typing “sqlplusS” would start sqlplus as the system account for the default instance. In this case. and this poses both security and logistical problems.ksh”. a “ls –l” command on the file should look something like: -rwxrwx--1 oracle dba 79 Nov 23 13:25 setup_passwords. www. From a security standpoint.profile. One other logistical issue comes up whenever help is needed to debug a script. This script should be placed in a directory common to all of those who need access. if it is run at the beginning of each script. First. which we will call “setup_passwords. One workable solution is the creation of a script. which contains a hard coded password. Typically. then the variables defined can be referenced at both the UNIX and embedded SQL levels.ksh If this is done in the . always proceed the call with a dot and a space so variables are visible to the script. must be protected so only authorized persons can view the scripts. For instance. From a logistical standpoint. When calling the script.

Embedded SQL By redirecting STDIN. This includes passwords! Sqlplus is simply a UNIX application. Regardless of the UNIX implementation. Simply be aware of the issue.org RMOUG Training Days 2001 . Scripts can be setup to get the passwords once the scripts start. all of the parameters passed in the first session may be shown.0 21:37:28 ttyp3 0:00.5 21:37:50 ttyp4 0:00. 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.07 sqlplus oracle 32400 4008 0.rmoug. For instance. sessions_current-1 sessions_current. and “C” programs can be setup to get environment variables as well. sessions_highwater from www.sessions_warning. Because of this. the following could be seen in another window: % ps -aef |grep sqlplus oracle 10828 10750 0 21:35:50 ttyp1 0:00 grep sqlplus oracle 10823 10808 0 21:35:44 ttyp3 0:00 sqlplus system/manager@devel % Figure 6 . but not all UNIX environments. systems should be tested befo re setting up such aliases. 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. the passwords will be available to anyone who does a “ps” command. Consider the following example: #! /bin/ksh .ksh $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off connect ${SYSTEM_CONNECT}.PS results on HP or Sun If the same thing is done on a Linux or Compaq/DEC environment. if “sqlplus system/manager” were typed at the UNIX prompt on a Sun or HP system. Another related consideration involves “C” programs or other scripts that take passwords as parameters. If a parameter password is passed to a UNIX application.sessions_max. and test accordingly. and Oracle strips off the parameters to sqlplus in some implementations. and the technique should be avoided. depending on the version of UNIX being used. /common/bin/setup_passwords. so this should not be a major problem. SQL or PL/SQL code can be directly coded into a KORN shell script.UNIX Shell Scripting for Oracle Ducat There is one very large warning here. Oracle has seen fit to fix this problem in some.PS results on Compaq or Linux This is generally a UNIX issue. another “ps” command will show the parameters have been stripped off by Oracle: % ps -aef |grep sqlplus oracle 10979 22719 0. and is subject to the same issues. and perform a “ps –aef” in another window.01 grep sqlplus % Figure 7 .

WORLD 0 0 0 % 1 Notice the first line of the output is a line containing “Connected.rmoug.ksh Connected. Consider the following script: #! /bin/ksh .----.UNIX Shell Scripting for Oracle Ducat v\$license.ksh. and end at the bottom.------. www.--------DEVEL.------. we do not always want to start at the top of the script. o Within the SQL area we issue a “connect” statement which references the SYSTEM_CONNECT variable When this script.” This line is the result of the “connect” statement and. This is required in a KSH script since UNIX attempts to translate the $ into environment variables. As any programmer is well aware. !! Figure 8 .global_name . quit. named l1. references to v$ tables must always include a “\” in front of the “$” character. /common/bin/setup_passwords. Never fear. the ability to create a subroutine is indispensable when creating complex code.Embedding SQL in a KSH script This script will connect to oracle using the default instance and perform a series of commands that show connection information. o When embedded in a KSH script. o The –s switch on the sqlplus command is included to remove the Oracle banner from the output.sessions_max. There are a few things to consider. Ksh provides this functionality in the form of functions embedded within the script. Instance Max Warning Current Highwater --------------. as of this time.sessions_warning.ksh __show_licenses() { $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off connect ${SYSTEM_CONNECT}. Embedded Subroutines (aka Functions) When scripting. the Embedded Subroutines section discusses sways of dealing with this issue. 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. o The /nolog switch is used to avoid passing the password on the command line. We use this technique to avoid passing the password in case this is run on a version that does not trim off parameters as discussed in the Password Management section. was run on a system where the default instance is named devel. there is no way to get sqlplus to stop producing that output.org RMOUG Training Days 2001 . the following results were produced: %l1.

There is no “do as I mean. Because of this. quit. but with a slight change. If the backslash were removed.------. but if the desire is to specifically match the period character. not as a part of a regular expression. the backslash is required.------. The grep command uses regular expression matching. etc. yet. If this is what is desired.out In this case.----. and code what you mean. we have included the definition of a function called __show_licenses. If this were done. but if sloppy style is used.global_name . The following would accomplish this: __show_licenses | grep –v “^Connected\. In short. but this can be accomplished by piping the results through grep to eliminate the offending output. The () following the function name indicates this is a function.WORLD 0 0 0 % 1 One interesting thing to note is the existence of the backslash character prior to the period character. This still does not get rid of the “Connected.Implementing a user-defined function in a KSH script In this example. This script produces the same output as the script in the Embedded SQL section.UNIX Shell Scripting for Oracle Ducat sessions_current-1 sessions_current.--------DEVEL. but the file scrap. the issue may be missed in later code. assume we changed the last line to: __show_licenses >scrap. An alternative syntax of “function __show_licenses” could be used if desired.out would contain the output. www. This example would work with or without the backslash. and then called by the code on the last line. we can redirect them through any means we desire.” so the results would look like: %l3. nothing would be sent to the screen. not what I say” mode in UNIX. the script would produce no output. the results of the function are pushed back through STDOUT. the function is first defined.” line discussed earlier.rmoug. When this script is run. The code for the function is bracketed by the “{}” characters. the code would eliminate lines containing things such as “ConnectedX”. then the period character can be used. resulting in some very hard to debug issues. The backslash character indicates that the following “special character” should be interpreted literally. mean what you say. This can be verified by commenting out the last line and running the script. “Connectedb”.ksh Instance Max Warning Current Highwater --------------. and the period represents “any one character”. !! } __show_licenses Figure 9 . When we call the function on the last line. sessions_highwater from v\$license.$” This grep command would eliminate any lines containing only the string “Connected.org RMOUG Training Days 2001 . For instance. the problem identified in that paragraph can be eliminated.

we can increase the usefulness of the script. Parameters passed into functions are handled the same way as parameters passed into scripts (as discussed in the Parameter Passing section). 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. Before writing this script.ksh aaa bbb aaa bbb test aaa % In this case. sessions_current-1 sessions_current.ksh __show_licenses() { $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off connect ${SYSTEM_CONNECT}@${1}. the first parameter passed into the script contains “aaa”.UNIX Shell Scripting for Oracle Ducat Passing Parameters Up until now. 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. and that value is passed as the second parameter to the __doit function. The following shows this. there are a few issues to be considered. Notice the parameter references on the connect line as well as on the call to __show_licenses. By using parameters. 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.sessions_max. /common/bin/setup_passwords.org RMOUG Training Days 2001 . and variables passed to the script must be passed to the function if they are to be used by the function.rmoug. 3 The default instance is the one used if no SID is passed on a connect string www. the script we have been building only works against the default instance3 .sessions_warning. #! /bin/ksh . sessions_highwater from v\$license. Getting back to our main script.global_name . and the echo command inside the __doit function will refer to the parameters passed in on the last line. The following run illustrates this: %s3.

This results in a connection to the default instance. !! } if [ $# -ne 1 ] . sessions_current-1 sessions_current. www. If this is not desired.rmoug. The following script demonstrate: #! /bin/ksh . we could hard code them.$” One interesting note is that if a parameter is not passed in.UNIX Shell Scripting for Oracle Ducat quit. Consider the following example: #! /bin/ksh . 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. a few lines of conditional logic could be added to the bottom in order to verify that a parameter was sent.$” else echo “ERROR: Invalid number of parameters specified” echo “ One instance name must be specified. quit. sessions_highwater from v\$license.sessions_warning. !! } __show_licenses ${1}| grep –v “^Connected\.sessions_max.then __show_licenses ${1}| grep –v “^Connected\. it ends up connecting as system/manager@.ksh __show_licenses() { $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off connect ${SYSTEM_CONNECT}@${1}.global_name . /common/bin/setup_passwords.” fi If we did not want to pass in the names of our instances. /common/bin/setup_passwords.org RMOUG Training Days 2001 .ksh __show_licenses() { $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off connect ${SYSTEM_CONNECT}@${1}.

$" __show_licenses devel|grep -v "^Connected\.WORLD 0 0 0 1 Instance Max Warning Current Highwater --------------. quit.----.sessions_max.------.--------SYSTEST.sessions_warning.----.------.--------DEVEL.--------PROD.UNIX Shell Scripting for Oracle Ducat 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.$" __show_licenses systest|grep -v "^Connected\.global_name . sessions_highwater from v\$license.------.$" This script would result in the following: %l6.------. sessions_current-1 sessions_current.------.WORLD 0 0 0 1 % www.------.rmoug.org RMOUG Training Days 2001 . !! } __show_licenses prod|grep -v "^Connected\.----.WORLD 0 0 0 1 Instance Max Warning Current Highwater --------------.ksh Instance Max Warning Current Highwater --------------.

sessions_current-1 sessions_current. In the previous example. quit. but it is still hard coded. the code must change. we added the -E options to the grep so we could also exclude blank lines.sessions_warning.WORLD DEVEL. we need to dynamically generate a list of instances on the machine we are running on.sessions_max.WORLD Max ----0 0 0 Warning ------0 0 0 Current ------0 0 0 Highwater --------1 1 1 This works well. 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.global_name .ksh __show_licenses() { $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off set heading ${heading} connect ${SYSTEM_CONNECT}@${1}.WORLD SYSTEST.$|^$" __show_licenses systest|grep -vE "^Connected\. The results of this code can be seen below: Instance --------------PROD. A few more modifications could correct the formatting issues: #! /bin/ksh . Global Functions There are times when it is helpful to have a small piece of code that can be called from multiple scripts. Notice the “set heading” command now references the “heading” variable which is set “on” or “off” in the shell area. This code could be added to www. The “^$” pattern matches any line containing only the beginning of the line immediately followed by the end of the line.org RMOUG Training Days 2001 . First. sessions_highwater from v\$license.UNIX Shell Scripting for Oracle Ducat While it works. This can be fixed via the creation of a global function as describes in the Global Functions section. !! } heading=on __show_licenses prod|grep -vE "^Connected\. /common/bin/setup_passwords.rmoug.$|^$" In this case. Next. a few changes were made. We added a “heading” environment variable and set it so only the first run would cause the heading to be printed by sqlplus. the results are not pretty.$|^$" heading=off __show_licenses devel|grep -vE "^Connected\. Every time an instance is added to the environment.

UNIX Shell Scripting for Oracle Ducat the script. If the code was copied to each script. The following script creates a function using the above logic to create an environment variable containing a list of all available instances.*ora_pmon_//" \ >/tmp/sids_$$. If the SID and connect information are different. For instance. modify all scripts. In the third command. appropriate changes will need to be made to the sample scripts.out for iName in `sort /tmp/sids_$$.out www.out ps -aef | \ grep ora_pmon | \ grep -vE 'sed|grep'| \ sed -e "s/^. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #! /bin/ksh gen_sid_list() { sid_list="" touch /tmp/sids_$$. For our purposes. system/manager@devel will connect to the instance with a SID of devel. we can take a look at these processes. the code could be modified to pick up those instances as well. For instance. Using the UNIX “ps” command. Our first task is to create the logic required to generate a list of instances on the local machine.rmoug. Every instance running on a machine creates what is known as a PMON process. If the code is in one place. Line numbers are included for reference purposes. Consider the following series of commands: %ps -aef |grep ora_pmon_ oracle 863 1 0 09:11 ? oracle 888 1 0 09:11 ? oracle 913 1 0 09:11 ? wducat 2584 2582 0 16:28 tty1 %ps -aef |grep ora_pmon_ |grep -v grep oracle 863 1 0 09:11 ? oracle 888 1 0 09:11 ? oracle 913 1 0 09:11 ? %ps -aef | \ grep ora_pmon_ | \ grep -vE 'sed|grep'| \ sed -e 's/^. but there are reasons that this standard may not be used. then one change would in effect. but it is something which could be useful in multiple areas. we will assume the tnsnames. maintenance would be a problem if the logic ever changed. but if another machine was added.org RMOUG Training Days 2001 . Most installations that I have been involved in use this standard. we modify the second grep to remove the sed command also added to the third command.do tnsping ${iName} >/tmp/ping_$$.out` . the first version may only work on the local machine. The result is a list of all of the currently running instances. The sed command tells the system to replace everything from the beginning of the line through the ora_pmon_ with nothing.*ora_pmon_//' devel prod systest % 00:00:00 00:00:00 00:00:00 00:00:00 ora_pmon_devel ora_pmon_prod ora_pmon_systest grep ora_pmon_ 00:00:00 ora_pmon_devel 00:00:00 ora_pmon_prod 00:00:00 ora_pmon_systest The first command shows us all of the Oracle pmon processes as well as our grep! The second command filters out the grep.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.

www.UNIX Shell Scripting for Oracle Ducat 16 17 18 19 20 21 22 23 24 25 eCount=`grep TNS. In our example. the function was placed in a file called functions. setting the variable Performs a tnsping on each instance to very if it is available.out done rm /tmp/sids_$$./tmp/ping_$$.ksh. except the results are sent to a temporary file Sets up a for loop which takes the sorted list of instance names in the temp file. The results of the ping are sent to a temp file for further review Counts the number of TNS errors returned from the ping Determines if the instance should be added to the variable Adds the instance to the variable Displays an error if problems were found connecting to the instance Cleans up temporary file Cleans up temporary file If the above script is placed in another file of functions.rmoug.out } The first thing done is the creation of a function called gen_sid_list.org RMOUG Training Days 2001 . The following is an analysis of the various lines in the function: Line Number 6 8 14 15 16 17 18 20 22 24 Purpose Creates an empty environment variable which will ultimately contain the list of instances Issues the same ps command discussed above. the script can be called from multiple scripts as long as the file of functions is called from each script. The placement of this function will be discussed later. and processes t hem one at a time.out|wc -l` if [ $eCount -eq 0 ] .then sid_list="${sid_list} ${iName}" else echo ERROR: Unable to connect to ${iName} fi rm /tmp/ping_$$.

The heading variable is then set to “on” for the first run.ksh at the top. /common/bin/setup_passwords. Nothing has changed in the __show_licenses function. If an existing instance is taken off-line. Each time through the loop. we call gen_sid_list to setup the sid_list environment variable. sessions_highwater from v\$license. This loop will be executed repeatedly for each instance. quit.global_name .org RMOUG Training Days 2001 . www.UNIX Shell Scripting for Oracle Ducat The following script as modified from the example in the Passing Parameters section uses this new function: #! /bin/ksh . /common/bin/functions. Next a “for loop” is setup to loop through the list of instances. this script will automatically find it. 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. it will no longer show up. the __show_licenses function is called. sessions_current-1 sessions_current. Finally.do __show_licenses ${iName}|grep -vE "^Connected\. !! } gen_sid_list heading=on for iName in $sid_list .rmoug.$|^$" heading=off done Notice the addition of a call to functions. This makes the gen_sid_list function available. First.ksh __show_licenses() { $ORACLE_HOME/bin/sqlplus -s /nolog <<!! set line 200 set feedback off set heading ${heading} connect ${SYSTEM_CONNECT}@${1}. the iName variable will contain the name of the next Oracle instance to process. the heading variable is set to “off” for the remaining instances. Next.sessions_warning. and the instance is specified via the iName variable that is passed in as a parameter. This code is now very generic. If a new instance is brought up on the machine.ksh .sessions_max.

Under close inspection. a number of shortcomings become obvious in the above example.org RMOUG Training Days 2001 . Scripting in Korn shell is very much like programming in any 3GL such as “C”.rmoug. the possibilities are endless. For instance. www. 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”. If the task is approached from a programmer’s point of view. the real work often begins as enhancements are implemented.UNIX Shell Scripting for Oracle Ducat Conclusion The process we just went through only scratches the surface of what can be accomplished with a well-written script.

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)//-->