Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unix Shell Scripting

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

the first line of every script is:

#!/path/to/shell (e.g. #!/bin/ksh).

The #! characters tell the system to locate the following pathname

Any file can be used as input to a shell by using the syntax:


ksh myscript

If the file is made executable using chmod,


chmod +x myscript

search for external commands using $PATH.

Can run a shell script using shellname scriptfile

run a single command using shellname -c "command"

Standard I/O redirection and piping with <,>,>>,|

Backgrounding commands with &

Home directory expansion using ~user (except for sh)

# comments

Command substitution using `command` (backtics)

Expand variables using $varname syntax

Conditional execution using && and ||

Line continuation with "\"

# as the first non-whitespace character on a line flags the line as a comment

\ as the last character on a line causes the following line to be logically joined before
interpretation

; as a separator between words on a line is interpreted as a newline.

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.

Shell internal settings


$PWD
Always set the current working directory (readonly)
$? (readonly)
Set to the exit status of the last command run, so you can test success or failure
$-
Set to the currently set options flags.
$IFS
Internal Field Separators: the set of characters

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.

ksh/bash additional features


$LINENO (readonly)
Always evaluates to the current line number of the script being executed - useful
for debugging.

Command Line (positional) arguments


$0, $1, $2, ... $9
The first 9 arguments are made available directly as $1-$9.
To access more than 9, use shift, or $*, $@. The variable $0 contains the name of the
script itself.

${10}, ${11}, ...


Positional arguments greater than 9 are set by ksh and bash. Remember to use
braces to refer to them
shift
discard $1 and renumber all the other variables. "shift N" will shift N arguments
at once.
$#
contains the number of arguments that were set (not including $0).
$*
contains all of the arguments in a single string, with one space separating them.
$@
similar to $*, but if used in quotes, it effectively quotes each argument and keeps
them separate

if the argument list is: a1 a2 "a3 which contains spaces" a4

$1=a1,

$2=a2,

$3=a3 which contains spaces,

$4=a4

$*=a1 a2 a3 which contains spaces a4

"$@"="a1" "a2" "a3 which contains spaces" "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

I got this from Tim Archer..

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.

The Basic Syntax

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.

A More Advanced Example

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:

• Checks command line parameters for the appropriate number of parameters.


• Exports the ORACLE_SID as passed in from the command line parameters.
• Runs the oraenv script for the specified ORACLE_SID to setup all the Oracle
specific environment parameters.
• Checks the return code from SQL Plus to determine if the SQL script successfully
ran and takes an appropriate course of action.

Create a file named test.sh and put the following code in it:

#!/bin/sh

# The name of this script


SCRIPT_NAME=test.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

echo "Starting Create PIN for ORACLE_SID: $ORACLE_SID"

###################################################################
#
# Run our SQL Plus Commands
#
###################################################################
sqlplus system/manager <<ENDOFSQL
whenever sqlerror exit sql.sqlcode;
select sysdate from dual;
exit;
ENDOFSQL

ERRORCODE=$?

#Check the return code from SQL Plus


if [ $ERRORCODE != 0 ]
then
echo "********************"
echo "ERROR: The SQL Plus Command Failed. ErrorCode: $ERRORCODE"
else
echo "********************"
echo "SQL Plus Successfully Ran. ErrorCode: $ERRORCODE"
fi

The format to run this script will then be:

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

Running PL/SQL Procedures And Passing In Unix Environment


Variables

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.

export TEST_VAR="HELLO WORLD"


sqlplus usfbanner/webster <<ENDOFSQL
whenever sqlerror exit sql.sqlcode;
set serveroutput on;
exec dbms_output.put_line('${TEST_VAR}');
exit;
ENDOFSQL

Running The Script Through Cron

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.

How can we schedule the procedure to run automatically ?

Using DBMS_JOB package,we can schedule the job.

There are number of built-in functions in that package to schedule a job.

Ex:

DBMS_JOB .SUBMIT

DBMS_JOB .RUN.

2) Using DBMS_SCHEDULER

THIS I SYNTAX FOR CREATING JOB

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.

Job definition window will open up.

Now enter all the relavent details along with the procedure name along with the parameters.

This will create a new job.


If you want to setup a cron to execute the procedure then you will have to write the shell
script to connect the database and execute the procedure.

then call the shell script file inside the cron script.

eg:

25 14 * * * /path of the shell script/filename.sh

You might also like