Unix Shell Scripting
Unix Shell Scripting
Unix Shell Scripting
# comments
\ as the last character on a line causes the following line to be logically joined before
interpretation
Every command (program) has a value or exit status which it returns to the calling
program
Filename Wildcards
*
Match zero or more characters.
?
Match any single character
[...]
Match any single character from the bracketed set. A range of characters can be
specified with [ - ]
[!...]
Match any single character NOT in the bracketed set.
Shell Variables
srcfile=dataset1
Creates (if it didn't exist) a variable named "srcfile" and sets it to the value
"dataset1".
set
Display all the variables currently set in the shell
unset srcfile
Remove the variable "srcfile"
export srcfile
Added srcfile to the list of variables which will be made available to external
program through the environment.
export
List all the variables currently being exported
Using variables
$srcfile
Prefacing the variable name with $ causes the value of the variable to be
substituted in place of the name.
${srcfile}
If the variable is not surrounded by whitespace (or other characters that can't be in
a name), the name must be surrounded by "{}" braces so that the shell knows
what characters you intend to be part of the name.
datafile=census2000
echo ${datafile}_part1.sas
${datafile-default}
Substitute the value of $datafile, if it has been defined, otherwise use the string
"default".
${datafile=default}
datafile has not been defined, set it to the string "default".
${datafile+default}
If variable datafile has been defined, use the string "default", otherwise use null
${datafile?"error message"}
Substitute the value of $datafile, if it has been defined, otherwise display
datafile: error message.
It is possible to export a variable just for the duration of a single command using the
syntax:
var=value command args
Login environment
$USER, $LOGNAME
Preset to the currently logged-in username
$TERM
The terminal type in which the shell session is currently
$PAGER
If set, this contains the name of the program which the user prefers to use for text
file viewing.
$EDITOR
If set, this contains the name of the program which the user prefers to use for text
file editing.
Process ID variables
$$ (readonly)
Set to the process ID of the current shell - useful in making unique temporary
files, e.g. /tmp/$0.$$
$PPID (readonly)
Set to the process ID of the parent process of this shell - useful for discovering
how the script was called.
$! (readonly)
Set to the process ID of the last command started in background - useful for
checking on background processes.
$1=a1,
$2=a2,
$4=a4
The set command, followed by a set of arguments, creates a new set of positional
arguments
Shell options
Startup options. ksh -options scriptname
-x
echo line to stderr before executing it
-n
read commands and check for syntax errors, but do not execute.
-a
all variables are automatically exported
-f
disable wildcard filename expansion (globbing)
set -x
Set an option within a shell script
$-
contains the currently set option letters
Command Substitution
`command`
A command (plus optional arguments) enclosed in backticks is executed and the
standard output of that command is substituted
ksh/bash syntax
$(command)
This syntax is functionally the same as backticks
$(<file)
This is equivalent to `cat file`,
Running SQLPlus and PL/SQL Commands From A Shell Script
1 08 2008
http://timarcher.com/?q=node/48
The need often arises to run Oracle SQL scripts or PL/SQL procedures from a shell
script. For instance, in my environment we run a lot of jobs through cron. Part of the job
may be to connect to the database and run a PL/SQL function or procedure. Below I will
describe how to do this, and some of the various “extras” that I include in my shell
scripts. All of the examples below have been tested on Oracle 10gR2 and RedHat AS 4.
In its simplest format, you can call SQLPlus from a shell script. The basic format of a
shell script doing this is:
#!/bin/sh
sqlplus system/manager@prod_db <<ENDOFSQL
select sysdate from dual;
exit;
ENDOFSQL
Try to create that shell script on your server and run it. Be sure to enter in the correct
connect string. You’re screen output should show all of the output from the SQL Plus
session that executes.
Now I will show you a more advanced script that I run on my servers. It builds off the
simple example above, except it does a few extra things:
Create a file named test.sh and put the following code in it:
#!/bin/sh
###################################################################
#
# Check for Invalid Command Line Arguments
# $1 = ORACLE_SID
#
###################################################################
if [ $# -lt 1 ]
then
echo "Usage: $SCRIPT_NAME <ORACLE_SID>"
echo "Example: $SCRIPT_NAME DWHSE PROD"
exit
fi
###################################################################
#
# Setup Script Variables
#
###################################################################
#This is the oracle_sid of the instance that the oracle environment
#will be setup for.
export ORACLE_SID=$1
#
# Initially we need some oracle path in the PATH for the dbhome command
# to be found. We reset the PATH variable to the proper oracle_home/bin
# below
#
export ORACLE_HOME=/usr/local/banner/oracle/product/current
export PATH=$ORACLE_HOME/bin:/usr/local/bin:$PATH
export ORAENV_ASK=NO
. /usr/local/bin/oraenv
export ORAENV_ASK=YES
###################################################################
#
# Run our SQL Plus Commands
#
###################################################################
sqlplus system/manager <<ENDOFSQL
whenever sqlerror exit sql.sqlcode;
select sysdate from dual;
exit;
ENDOFSQL
ERRORCODE=$?
./test.sh ORACLE_SID
You’ll need to modify a few sections of the script to work in your environment as
described below:
• In the section labeled Check for Invalid Command Line Arguments you will want
to change the script to take an ORACLE_SID appropriate for your environment.
The SID’s that are valid in my environment are PROD and DWHSE.
• Change the connect string from system/manager to be what is required for your
environment. There is no need to specify the Oracle SID in this part of the
connect string since the beginning of the script exports the appropriate SID.
• Plug in your own SQL to run within SQL Plus. In the example I gave you it will
always succeed since selecting sysdate from dual will always work.
Within the section specifying the SQL to run you can even call PL/SQL functions and
procedures. If you want to call a PL/SQL function or procedure, make sure you prefix the
procedure call with the keyword exec. Furthermore, you can pass your Unix environment
variables into your SQL Plus session. The following example creates the environment
variable named TEST_VAR and then runs SQL Plus calling DBMS_OUTPUT to print out
the value in the variable.
Once you are able to get a script created that performs all of the appropriate actions that
you need to do, you can automate running it through cron. This is the simple part.
• As the user who will run the script (probably the oracle user), edit the crontab.
crontab –e
• Add a line to run your script at the time you desire. For example, I have the
following entry in the crontab for my oracle user that will run a script to send
emails to people who new user accounts have been generated for.
30 13 * * * /usr/local/banner/scripts/send_new_account_email.shl
PROD
The script will run at 1:30pm every day connecting to the PROD database
instance. Lastly, the output from running this script will be emailed to the oracle
user for my review. The emailing of any output is standard cron functionality.
Ex:
DBMS_JOB .SUBMIT
DBMS_JOB .RUN.
2) Using DBMS_SCHEDULER
dbms_scheduler.create_job(
ob_name IN VARCHAR2,
job_type IN VARCHAR2,
job_action IN VARCHAR2,
number_of_arguments IN PLS_INTEGER DEFAULT 0,
start_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL,
repeat_interval IN VARCHAR2 DEFAULT NULL,
end_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL,
job_class IN VARCHAR2 DEFAULT 'DEFAULT_JOB_CLASS',
enabled IN BOOLEAN DEFAULT FALSE,
auto_drop IN BOOLEAN DEFAULT TRUE,
comments IN VARCHAR2 DEFAULT NULL);
procdures can be scheduled to execute periodically by using the job scheduler in windows
based systems or by using the cron in unix based systems.
GOTO toad->click on JOB tab-> right click on the list below and select create a new job menu.
Now enter all the relavent details along with the procedure name along with the parameters.
then call the shell script file inside the cron script.
eg: