Wednesday, April 8, 2009

Shell Script Constructs

Shell Script Constructs

case word in pattern ) ;;esac
for i in expression; do #codedone
for (i = 0; i < 10; i++); do #codedone
function_name () { #code}
if [ condition ]; then #codeelif [ condition ]; then #codeelse #codefi
if [ condition ]; then #codeelse #codefi
if [ condition ]; then #codefi
until [ condition ]; do #codedone
while [ condition ]; do #codedone

In Details:-

Common environment variables

PATH - Sets the search path for any executable command. Similar to the PATH variable in MSDOS.

HOME - Home directory of the user.
MAIL - Contains the path to the location where mail addressed to the user is stored.

IFS - Contains a string of characters which are used as word seperators in the command line. The string normally consists of the space, tab and the newline characters. To see them you will have to do an octal dump as follows:
$ echo $IFS | od -bc
PS1 and PS2 - Primary and secondary prompts in bash. PS1 is set to $ by default and PS2 is set to '>' . To see the secondary prompt, just run the command :

$ ls |... and press enter.

USER - User login name.

TERM - indicates the terminal type being used. This should be set correctly for editors like vi to work correctly.

SHELL - Determines the type of shell that the user sees on logging in.

Note: To see what are the values held by the above environment variables, just do an echo of the name of the variable preceeded with a $. For example, if I do the following:

$ echo $USERravi... I get the value stored in the environment variable USER.

Some bash shell scripting rules

1) The first line in your script must be

#!/bin/bash ... that is a # (Hash) followed by a ! (ban) followed by the path of the shell. This line lets the environment know the file is a shell script and the location of the shell.

2) Before executing your script, you should make the script executable. You do it by using the following command:

$ chmod ugo+x your_shell_script.sh3) The name of your shell script must end with a .sh . This lets the user know that the file is a shell script. This is not compulsary but is the norm.

Conditional statements

The 'if' Statement - evaluates a condition which accompanies its command line. Those words marked in blue are compulsory. But those marked in red are optional.


if condition_is_truethenexecute commandselseexecute commandsfiif condition also permits multiway branching. That is you can evaluate more conditions if the previous condition fails.

if condition_is_truethenexecute commandselif another_condition_is_truethenexecute commandselseexecute commandsfiExample :

if grep "linuxhelp" thisfile.htmlthenecho "Found the word in the file"elseecho "Sorry no luck!"fiif's companion - test

test is an internal feature of the shell. test evaluates the condition placed on its right, and returns either a true or false exit status. For this purpose, test uses certain operators to evaluate the condition. They are as follows:

Relational operators

-eq Equal to-lt Less than-gt Greater than-ge Greater than or equal to-lt Less than-le Less than or equal to File related tests

-f file True if file exists and is a regular file-r file True if file exists and is readable-w file True if file exists and is writable-x file True if file exists and is executable-d file True if file exists and is a directory-s file True if file exists and has a size greater than zero.String tests

-n str True if string str is not a null string-z str True if string str is a null stringstr1 == str2 True if both strings are equalstr1 != str2 True if both strings are unequalstr True if string str is assigned a value and is not null.Test also permits the checking of more than one expression in the same line.

-a Performs the AND function-o Performs the OR functionExample:

test $d -eq 25 ; echo $d... which means, if the value in the variable d is equal to 25, print the value.

test $s -lt 50; do_something

if [ $d -eq 25 ]thenecho $dfiIn the above example, I have used square brackets instead of the keyword test - which is another way of doing the same thing.

if [ $str1 == $str2 ]then do somethingfiif [ -n "$str1" -a -n "$str2" ]then echo 'Both $str1 and $str2 are not null'fi... above, I have checked if both strings are not null then execute the echo command.

Things to remember while using test

If you are using square brackets [] instead of test, then care should be taken to insert a space after the [ and before the ].

Note: test is confined to integer values only. Decimal values are simply truncated.

Do not use wildcards for testing string equality - they are expanded by the shell to match the files in your directory rather than the string.

Case statement
Case statement is the second conditional offered by the shell.

case expression inpattern1) execute commands ;;pattern2) execute commands ;;...esacThe keywords here are in, case and esac. The ';;' is used as option terminators. The construct also uses ')' to delimit the pattern from the action.


...echo "Enter your option : "read i;case $i in 1) ls -l ;; 2) ps -aux ;; 3) date ;; 4) who ;; 5) exitesacNote: The last case option need not have ;; but you can provide them if you want.

Here is another example:

case `date |cut -d" " -f1` in Mon) commands ;; Tue) commands ;; Wed) commands ;; ...esacCase can also match more than one pattern with each option.You can also use shell wild-cards for matching patterns.

...echo "Do you wish to continue? (y/n)"read anscase $ans in Y|y) ;;[Yy][Ee][Ss]) ;; N|n) exit ;;[Nn][Oo]) exit ;; *) echo "Invalid command"esac
In the above case, if you enter YeS, YES,yEs and any of its combinations, it will be matched.

This brings us to the end of conditional statements.

Looping Statements
while loop
Syntax :

while condition_is_truedo execute commandsdoneExample:

while [ $num -gt 100 ]do sleep 5donewhile :do execute some commandsdoneThe above code implements a infinite loop. You could also write 'while true' instead of 'while :' .

Here I would like to introduce two keywords with respect to looping conditionals. They are break and continue.

break - This keyword causes control to break out of the loop.

continue - This keyword will suspend the execution of all statements following it and switches control to the top of the loop for the next iteration.

until loop

Until complements while construct in the sense that the loop body here is executed repeatedly as long as the condition remains false.


until falsedo execute commandsdoneExample:

...until [ -r myfile ]dosleep 5doneThe above code is executed repeatedly until the file myfile can be read.

for loop
Syntax :

for variable in listdoexecute commandsdoneExample:

...for x in 1 2 3 4 5do echo "The value of x is $x";done
Here the list contains 5 numbers 1 to 5. Here is another example:

for var in $PATH $MAIL $HOMEdo echo $vardoneSuppose you have a directory full of java files and you want to compile those. You can write a script like this:

...for file in *.javado javac $filedoneNote: You can use wildcard expressions in your scripts.

A few special symbols and their meanings w.r.t shell scripts

$* - This denotes all the parameters passed to the scriptat the time of its execution. Which includes $1, $2and so on.$0 - Name of the shell script being executed.$# - Number of arguments specified in the command line.$? - Exit status of the last command.The above symbols are known as positional parameters. Let me explain the positional parameters with the aid of an example. Suppose I have a shell script called . Now I execute this script in the command line as follows :

$ ./ linux is a robust OS... as you can see above, I have passed 5 parameters to the script. In this scenario, the values of the positional parameters are as follows:

$* - will contain the values 'linux','is','a','robust','OS'.
$0 - will contain the value - the name of the script being
$# - contains the value 5 - the total number of parameters.

$$ - contains the process ID of the current shell. You can use this parameter while giving unique names to any temporary files that you create at the time of execution of the shell.

$1 - contains the value 'linux'
$2 - contains the value 'is'
... and so on.

The set and shift statements
set - Lets you associate values with these positional parameters .
For example, try this:

$ set `date`$ echo $1$ echo $*$ echo $#$ echo $2shift - transfers the contents of a positional parameter to its immediate lower numbered one. This goes on as many times it is called.

Example :

$ set `date`$ echo $1 $2 $3$ shift$ echo $1 $2 $3$ shift$ echo $1 $2 $3To see the process Id of the current shell, try this:

$ echo $$2667Validate that it is the same value by executing the following command:

$ ps -f |grep bashread statement

Make your shell script interactive. read will let the user enter values while the script is being executed. When a program encounters the read statement, the program pauses at that point. Input entered through the keyboard id read into the variables following read, and the program execution continues.


#!/bin/shecho "Enter your name : "read nameecho "Hello $name , Have a nice day."Exit status of the last command

Every command returns a value after execution. This value is called the exit status or return value of the command. A command is said to be true if it executes successfully, and false if it fails. This can be checked in the script using the $? positional parameter.

Here I have given a concise introduction to the art of bash shell scripting in Linux. But there is more to shell scripting than what I have covered. For one, there are different kinds of shells, bash shell being only one of them. And each shell has a small variation in its syntax. Like the C shell for example, which uses a syntax close to the C language for scripting. But what I have covered above applys to all the shells.

Easy way of Data Guard / Standby Database 10g (on windows)

Data Guard - Oracle's Answer to Disaster Recovery

  • See how to quickly implement a Data Guard physical standby database in a day.
  • Learn how to switch over to your standby database in minutes.
  • Possibly offload your batch reporting workload to your standby database.
  • Replace your forebodings about crashes with "Don't worry ... be happy!"

Data Guard/Standby 10g (on windows)

Default (Maximum Performance) primary site= dba1 standby site= dba2

Pr Site:

  • Archive Mode
    SQL>archive log list
    SQL> shutdown immediate
    SQL> startup mount
    SQL> alter database archivelog;
    SQL> alter database open;
    SQL> archive log list
  • FORCE LOGGING must be enabled:SQL> select force_logging from v$database;SQL> alter database force logging;
  • MAXLOGFILES >= (2 * Current Redo Log Groups) + 1:

    SQL> select records_used "Current Groups",records_total "Max Groups",
    "Recreate MAXLOGFILES?"
    from v$controlfile_record_section where type = 'REDO LOG';

    If not available please increase MAXLOGFILES form Control file to trace

  • Listener
    Create Listener
  • Tnsnames
    Configure tnsnames both
  • Edit sqlnet.ora (Optional)

  • Create a password file if it doesn't exist.$orapwd file=pwdPRIM.ora password=xxx force=y

Note: sys passwd on Primayr db MUST be the same as the sys passwd on Standby db, otherwise no Log hipping is possible.

Main Task :

· Create pfile from spfile ( pr. database)
create pfile='d:\oracle\db1\oradata\standby_pfile.ora' from spfile;

· Create StandBy Control file from pr. database
· goto database Mount mode

· alter database create standby controlfile as 'd:\oracle\db1oradata\standby_controlfile.ctl';

· shutdown pr. Database

· Modify pfile for Dr. Database

background_dump_dest = /pgms/oradata/PPRD2/bdump # Location for Dr side
core_dump_dest = /pgms/oradata/PPRD2/cdump# Location for Dr side
user_dump_dest = /pgms/oradata/PPRD2/udump # Location for Dr side
audit_file_dest = /pgms/oradata/PPRD2/audit # Location for Dr side

#(Dr. database location)

DB_NAME=dba1 #(Pr databse SID)
DB_UNIQUE_NAME=dba2 #(Dr databse SID)
SERVICE_NAMES=dba2 #(Dr databse SID) # Connect String or SERVICE_NAMES


LOG_ARCHIVE_DEST_1= 'LOCATION=G:\oracle\product\archivelog





  • cold backup (all data file without temp file)
  • Copy to standby_controlfile.ctl, pfile, all cold datafile backup.

    Modify Pfile for PR Database:

    LOG_ARCHIVE_DEST_1= 'LOCATION=G:\oracle\product\archivelog


    · dr database startup
    SQL> startup nomount pfile=’location’

SQL> alter database mount standby database;

SQL> alter database recover managed standby database disconnect from session;

SQL> exit

· pr database
SQL> startup

** stop & start both pr. & dr. database listener

Finish your Standby database for Maximum performance mode

Startup standby Database to Recovery mode

1. startup nomount -----pfile='G:\oracle\pfile\init.ora.12'
2. alter database mount standby database;
3. alter database recover managed standby database disconnect from session;
4. alter database recover managed standby database cancel;

startup standby for checkiong of reporting purpose
5. alter database open read only;
6. shutdown immediate
7. (1-6)

verifing the standby
SQL> select sequence#, first_time, next_time from v$archived_log order by sequence#SQL> /
SQL> select sequence#, archived, applied from v$archived_log order by sequence#;/

Role switchover (from Primary to standby)

To Primary site===================

SQL> SELECT switchover_status FROM v$database;
SQL> SELECT username FROM v$session

WHERE status = 'ACTIVE' AND username IS NOT NULL AND username != 'SYS';
no rows selected
(SQL> alter database commit to switchover to physical standby;)

if SESSIONS ACTIVE remain then

SQL> alter database commit to switchover to physical standby with session shutdown;
Database altered.
SQL> shutdown immediate

ORA-01507: database not mounted
ORACLE instance shut down.

SQL> startup nomountORACLE instance started.
Total System Global Area 612368384 bytes

Fixed Size 1250428 bytes

Variable Size 155192196 bytes

Database Buffers 448790528 bytes

Redo Buffers 7135232 bytes

SQL> alter database mount standby database;
Database altered.
SQL> alter system set log_archive_dest_state_2 = defer;
System altered.
SQL> alter database recover managed standby database disconnect from session;
Database altered.

SQL> select sequence#, first_time, next_time 2* from v$archived_log order by sequence#

SQL> /
SQL> select sequence#, archived, applied from v$archived_log order by sequence#;/

To standby site===========================
SQL> select switchover_status from v$database;
SQL> alter database commit to switchover to primary;
Database altered.
SQL> shutdown immediateORA-01109: database not open
Database dismounted.ORACLE instance shut down.

SQL> startup open

ORACLE instance started.
Total System Global Area 612368384 bytesFixed Size 1250452 bytesVariable Size 167775084 bytesDatabase Buffers 440401920 bytesRedo Buffers 2940928 bytesDatabase mounted.

Database opened.

SQL> alter system set log_archive_dest_state_2 =enable;
System altered.
SQL> alter system archive log current;
System altered.
SQL> alter tablespace temp add tempfile 'G:\oracle\product\10.2.0\oradata\dba2\temp1.dbf' size 50m;
Tablespace altered.
SQL> alter system switch logfile;
System altered.
SQL> alter system switch logfile;
System altered.


  • Data Guard provides an automated standby database which can essentially eliminate downtime of your production data.
  • Setup is easy and fairly straightforward.
  • Maintenance is minimal.
  • Switchovers and failovers can be done within a few minutes.
  • Reporting can be offloaded to the standby to ease the workload on the primary.
  • And … It's Free! (Included with Enterprise Edition)

For Date Output/input in Developer6i application

For Date Output/input in Developer6i application

CMD > Regedit

In Oracle_home string value


restore and recover a database to another host with RMAN Backup

1) RMAN> backup database; (source db)

2)Transfer this two backup pieces to target machine from source.

3)Determine the DBID of source machine.

SQL> select dbid from v$database;
( DBA (DBID=1130256874) ERA_h (three Schema database backup) (Personal))

4) Now perform task on target machine
$export ORACLE_SID=dba

Then connect to rman,

$ rman target /

5)Set DBID and restore spfile to pfile.

RMAN> set dbid 3386862614
RMAN> startup nomount
RMAN> restore spfile to pfile '/oracle/app/oracle/product/10.2.0/db_1/dbs/initdbase1.ora' from '/oradata2/o1_mf_s_654016132_421c64vl_.bkp';

6)start the instance with pfile.
RMAN> STARTUP FORCE NOMOUNT PFILE='/oracle/app/oracle/product/10.2.0/db_1/dbs/initdbase1.ora';

7)Restore controlfile and mount the database.RMAN> RESTORE CONTROLFILE FROM '/oradata2/o1_mf_s_654016132_421c64vl_.bkp';

8)From SQL*Plus determine the data file and redo log file name.

9)Catalog your backuppiece.

RMAN> catalog backuppiece '/oradata2/o1_mf_nnndf_TAG20080506T150716_421c355f_.bkp';

RMAN> list backup;

10)Make a script by issuing SET NEWNAME if you want different file name other than source.
In the script issue SET UNTIL clause and restore and recover database.

RMAN> @/export/home/oracle/rman

RMAN> run{
2> set newname for datafile 1 to '/oradata2/DBA/system01.dbf';
3> set newname for datafile 2 to '/oradata2/DBA/undotbs01.dbf';
4> set newname for datafile 3 to '/oradata2/DBA/sysaux01.dbf';
5> set newname for datafile 4 to '/oradata2/DBA/users01.dbf';
6> set newname for datafile 5 to '/oradata2/DBA/tbs201.dbf';
7> set newname for datafile 6 to '/oradata2/DBA/after_01.dbf';
8> set newname for datafile 7 to '/oradata2/DBA/after_02.dbf';
9> set newname for datafile 8 to '/oradata2/DBA/after_03.dbf';
10> set newname for datafile 1 to '/oradata2/DBA/system01.dbf';
12> SET UNTIL SCN 745212;
16> }

11)Open the Database resetlogs option.
RMAN> alter database open resetlogs;

frm-41211 integration error: ssl failure running another product

You receive the above error when using RUN_PRODUCT or RUN_REPORT_OBJECT in forms:

This can occur for a number of reasons. Below are a number of Causes and Solutions
Cause no 1)

Cause of this error may be......

"Report Server" property of "Reports" object is not set.

you can try to solve this problem by following guideline.......

The "Report Server" property of the "Reports" object should be set. This could be either set in "Report Server" property of the "Reports" object during design time (in Forms Builder),


could be programaticaly set using SET_REPORT_OBJECT_PROPERTY built-in similar to following :

set_report_object_property(l_repid, REPORT_SERVER, 'name_of_reports_server');

where l_repid stands for the id of Reports Object

Cause no 2) - Multiple Calls of RUN_PRODUCT/RUN_REPORT_OBJECT:

If you run multiple Reports from Forms e.g. in a loop with
Run_report_object or Run_product and the Communicaton Mode is
Asynchronous you will get Error FRM-41211 INTEGRATION

1) Use SYNCHRONOUS instead of ASYNCHRONOUS when running multiple
reports. This way the next report will not run until the first

2) Use ON-ERROR trigger on forms-level as follows:

lv_errcode number := error_code;
lv_errtype varchar2(3) := error_type;
lv_errtxt varchar2(80) := error_text;
IF (lv_errcode = 41211) THEN null;
message(lv_errtype || '-' || to_char(lv_errcode) || ': ' ||
raise form_trigger_Failure;
This will allow you to bypass the FRM-41211 error if you
are receiving it in error.

3) Introduce a small delay between the two calls. For instance,
executing either the PAUSE command or create a TIMER between
the successive RUN_PRODUCT/RUN_REPORT_OBJECT commands.
Cause no 3 - Environment problems:

The same report may be able to run successfully on another machine.
The form may compile and run successfully, it is only when issuing
the call to RUN_PRODUCT or RUN_REPORT_OBJECT that the above error occurs.


Verify that the REPORTS60_PATH is set correctly.
The REPORTS60_PATH should point to a directory which contains
the executable files (for example,.rdf or .rep files) that are
used by Oracle Forms to run the report. Also make sure that the environment
variable is spelled properly (REPORTS60_PATH and not REPORT60_PATH).
This is the environment variable that is used by the system to find your
reports executables.

Cause no 4 - Memory Problems:  

Integration errors are most commonly caused by memory resource problems.
This type of error can also occur if you do not have enough REAL ( CONVENTIONAL )
memory necessary to launch Reports or Graphics.
A general recommendation is 8 MB of Memory for one runtime component
and 3 MB for each additional Runtime you want to run concurrently.
16 MB of memory are recommended for one Designer Component and
an additional 4MB for each Designer you want to run concurrently.

Cause no 5) Incompatible Report/Graphics Version:
Make sure that you have properly installed the Oracle Graphics,
Oracle Reports and Oracle Book version that is compatible
with the Oracle Forms version that you are running.

Cause no 6) LAN Installation of Developer:

You are using a Windows platform using a LAN install
(the Oracle products are installed on a network drive).
When you issue the RUN_PRODUCT built-in to call Oracle Reports
from Oracle Forms, the following error occurs:
FRM-41211: Integration error -- SSL failure running another product
Running the report stand-alone can result in the following
error: REP-118 : Unable to create a temporary file.


7) Last Cause may be .....

May be this problem is for the REPORT DEVELOPER or RUNTIME not installed in your machine or might be one that is installed is of older version... there is a conflict between forms developer and reports run-time . be sure that your form is not corrupted and reinstall reports.

Last solution..... you can reinstall of the reports
( i solved my problem by this way)

1. close all applications that are runnig
[especially antivirus progs]

2. remove in the registry the reports path key

3. install reports

4. set your reports path in the register.

5. reboot computer
6. close all applications that would be start when windows start form and call a report

TNS-12542: address already in use.

TNS-12542: address already in use.
Problem is caused due to the fact that the free ports in the windows client has been exhausted and it is trying to make use of a port which is in TIME_WAIT state which gives the error tns-12542: address already in use.

FixThere are 2 solutions available:

1.) increase the free port range:


Start Registry Editor (Regedt32.exe).Locate the following key in the registry:HKEY_LOCAL_MACHinE\SYSTEM\CurrentControlSet\Services\Tcpip\ParametersOn the Edit menu, click Add Value, and then add the following registry value:

Value Name: MaxuserPort Data Type: REG_DWORD
Value: 65534 Valid Range: 5000-65534 (decimal)
Default: 0x1388 (5000 decimal)

Description: This parameter controls the maximum port number used when an application requests any available user port from the system. Normally, ephemeral (that is, short-lived) ports are allocated between the values of 1024 and 5000 inclusive.

2.) Decrease the value for TIME_WAIT state:


TcpTimedWaitDelay (new in Windows NT versions 3.51 SP5 and later)

Key: Tcpip\Parameters Value Type: REG_DWORD - Time in seconds

Valid Range: 30-300 (decimal)Default: 0xF0 (240 decimal)

Description: This parameter determines the length of time that a connection will stay in the TIME_WAIT state when being closed. While a connection is in the TIME_WAIT state, the socket pair cannot be re- used. This is also known as the "2MSL" state, as by RFC the value should be twice the maximum segment lifetime on the network. See RFC793 for further details.