Shell Script piping - shell

#!/bin/sh
output=ANIL;
#
# Ask user for database inputs
#
echo -n "Enter Database Server Hostname: "
read dba_host
echo -n "Enter Database SID: "
read dba_sid
echo -n "Enter DBA User: "
read dba_usr
echo -n "Enter DBA password: "
read dba_pwd
echo -n "What daemon are we using: "
read daemon_str
#
# Loop to connect to database and exit if something is found
#
while :
do
output=`sqlplus $dba_usr/$dba_pwd#$dba_sid <<+ | grep '^-' | sed 's/-//'
set serveroutput on
DECLARE
command VARCHAR2(50);
return_name VARCHAR2(30);
value VARCHAR2(10000);
status INT;
system_time TIMESTAMP := SYSTIMESTAMP;
WHILE TRUE
BEGIN
status := DBMS_PIPE.RECEIVE_MESSAGE($daemon_str);
IF status = 0 THEN
DMS_PIPE.UNPACK_MESSAGE(command);
END IF;
IF command = "STOP" THEN
DBMS_OUTPUT.PUT_LINE('STOP was encountered') >> file.log;
DBMS_OUTPUT.PUT_LINE(system_time) >> file.log;
BREAK
ELSIF command = "SYSTEM" THEN
DBMS_PIPE.UNPACK_MESSAGE(return_name);
DBMS_PIPE.UNPACK_MESSAGE(value);
EXIT
$value
ELSIF command = "SQL"
DBMS_PIPE.UNPACK_MESSAGE(return_name);
DBMS_PIPE.UNPACK_MESSAGE(value);
EXECUTE IMMEDIATE value;
ELSE
nap(10)
EXCEPTION
WHEN OTHERS THEN
dbms_ouput.put_line('Unknown Input Error') >> file.log;
DBMS_OUTPUT.PUT_LINE(system_time) >> file.log;
DBMS_PIPE.PACK_MESSAGE('done');
DBMS_PIPE.PACK_MESSAGE(status);
status := DBMS_PIPE.SEND_MESSAGE(return_name,10);
END;
dbms_output.put_line(chr(10) || '-' || command);
END;
/
exit
+`
echo $output
done
I am trying to convert a c code block to what you see now a shell script block. I am just a beginner in this coding language and was wanting to know if anyone is seeing something I am not. To sum up what I am trying to accomplish is ask user for the oracle database they want to connect to then keep connection and receive things through pipe. Then the usual of unpacking, outputting errors and such. Then sending it back through same pipe. Any input on possible syntax or anything at all that could be causing this to constantly echo out nothing but blank lines from while loop.

Related

Redirecting PostgreSQL Notices to a Bash Array

I have a PostgreSQL statement which raises notices. I wish to redirect this output into a bash array. I have tried the following:
declare -a MYARRAY
MYARRAY=( `psql -U $db_username -h $DATABASE_HOST $DATABASE_NAME -c \
"DO \\$\\$ DECLARE
mySite varchar;
myResult RECORD;
BEGIN
RAISE NOTICE 'current_site, folder, path';
FOR mySite IN SELECT name from public.app_info
LOOP
{Confidential Data here!}
LOOP
RAISE NOTICE '%,%,%', myResult.current_site, myResult.folder, myResult.path;
END LOOP;
END LOOP;
END\\$\\$"` )
echo "These are the files"
for i in ${MYARRAY[#]}; do
echo $i
done
When I run my script my notices from the query are printed to my window but they are not added into the array. I have also tried this with a variable instead of an array, with no luck.
Notices are printed into stderr so change
END\\$\\$"` ) to END\\$\\$" 2>&1` )
but array will contain also texts like NOTICE: and DO so you have to filter them out

How to call oracle function from a Korn Shell Script?

I have a user defined oracle function that returns a number that can be greater than 255. I call that function from a shell script using sql plus, it returns the value, for eg 296, but the scripts accepts it as 40, which is because the script can only accept return codes from 0-255.
This is how i am currently receiving the value
echo ${PASSWORD} | sqlplus ${USERNAME}#${SID} #$SQL getnumber.sql $PARAM> ${LOG}
number=$?
getnumber.sql has
set serveroutput on size 100
VARIABLE rc NUMBER;
call function_get_number('&2') into :rc;
print rc;
exit :rc;
How can i preserve the return value? Should i write it to a file? if so how/where
Script getnumber.sh:
cat << EOF | sqlplus /S /nolog >${LOG}
conn ${USERNAME}/${PASSWORD}#${SID}
set serveroutput on size 100
VARIABLE rc NUMBER;
exec :rc := function_get_number('$PARAM');
SELECT 'RETVAL:' || :rc || ':' theval FROM dual;
EOF
RC=$( grep '^RETVAL:' ${LOG} | cutr -d":" -f2 )
echo $RC

not able to call the procedure in shell script

I have the following shell script register as host executable calling a procedure, that will call a concurrent program in oracle , when I submit the job, it has no concurrent program spawn, I am using the same method in other instance before and it will work, wonder if I missed anything.
#!/bin/ksh
#--------------------------------------------------
# Get the current date
#--------------------------------------------------
HISTDATE=`date +"%m%d%y%H%M%S"`
#--------------------------------------------------
# Input Paramenters
#--------------------------------------------------
APPSPW=${1}
USERID=${2}
USERNAME=${3}
REQID=${4}
INTERFACE_PATH=${5}
AS_OF_DATE=${6}
FILENAME=${7}
echo "+---------------------------------------------------------------------------+"
echo "| 1. Get FTP Info"
echo "+---------------------------------------------------------------------------+"
echo "Request Id : " $REQID
echo "Used Id : " $USERID
echo "User Name : " $USERNAME
echo "Interface Path : " $INTERFACE_PATH
echo "As of Date : " $AS_OF_DATE
echo "File Name : " $FILENAME
if [ -d $INTERFACE_PATH ]; then
echo "- 1.1 Folder "$INTERFACE_PATH" exists"
else
echo "- 1.1 Folder "$INTERFACE_PATH" does not exist"
exit 1
fi
echo "+---------------------------------------------------------------------------+"
echo "| 2. Check File Exist or Not"
echo "+---------------------------------------------------------------------------+"
cd $INTERFACE_PATH
V_FILENAME="${FILENAME}${AS_OF_DATE}"
for files in `ls ${V_FILENAME}*`
do
echo "File Name : " $files
INPUT_FULL_FILENAME="${INTERFACE_PATH}${files}"
if [ -s $INPUT_FULL_FILENAME ]; then
echo "File found, now proceed SQL loader"
sqlplus $APPSPW <<ENDOFSQL
connect $APPSPW
SET SERVEROUTPUT ON
DECLARE
P_ERRBUFF VARCHAR2(4000);
P_ERRCODE VARCHAR2(100);
P_FULL_PATH VARCHAR2(400);
ln_request_id NUMBER;
lv_appl_name VARCHAR2(10) := 'XHGL';
lvc_sqlloader1 VARCHAR2(30) := 'XHGL_DCASS_STG';
lv_req_status1 VARCHAR2(1);
lv_msg VARCHAR2(1000);
ln_user_id NUMBER;
ln_resp_id NUMBER;
ln_resp_appl_id NUMBER;
BEGIN
BEGIN
SELECT APPLICATION_ID
INTO ln_resp_appl_id
FROM FND_APPLICATION
WHERE APPLICATION_SHORT_NAME = 'XHGL';
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('Failed to get ln_resp_appl_id');
END;
BEGIN
SELECT FND_GLOBAL.USER_ID
INTO ln_user_id
FROM DUAL;
END;
dbms_output.put_line('ln_user_id = ' || ln_user_id);
BEGIN
SELECT FND_GLOBAL.RESP_ID
INTO ln_resp_id
FROM DUAL;
END;
P_FULL_PATH := TO_CHAR('${INPUT_FULL_FILENAME}');
dbms_output.put_line('P_FULL_PATH = ' || P_FULL_PATH);
FND_GLOBAL.APPS_INITIALIZE(USER_ID => ln_user_id,
RESP_ID => ln_resp_id,
RESP_APPL_ID => ln_resp_appl_id);
XHGL_DCASS_INBOUND_PKG.SUBMIT_CCMS_STG( P_ERRBUFF, P_ERRCODE, P_FULL_PATH );
dbms_output.put_line('P_ERRBUFF = ' || P_ERRBUFF);
dbms_output.put_line('P_ERRCODE = ' || P_ERRCODE);
END;
/
exit
ENDOFSQL
fi
done
exit 0

Execute psql query in bash

I have a problem with executing a psql-query in a bash script.
Below is my code.
run_sql(){
sql_sel="$1;";#sql select
table=$2;#table name
for i in "${!GP_SERVER_NAMES[#]}"
do
logmsg "Executing [$sql_sel] on "${GP_SERVER_NAMES[$i]}": " $loglvl;
result_host[$i]=`${PSQL_HOST[$i]}${sql_sel}`;
#result_host[$i]=cleanresult "`$(${PSQL_HOST[$i]} "$tx_fix $sql_sel" 2>&1`");
if [[ `checkresult "${result_host[$i]}"` != 'true' ]]; then
logmsg "Error occured during sql select: Result for "${GP_SERVER_NAMES[$i]}" '${table}': ${result_host[$i]};" '1' '1';
raise_alarm "${GP_SYNC_SQL_ERR}" "${i}" "${table}" "${result_host}";
fi
logmsg "Result for" ${GP_SERVER_NAMES[$i]} " '${table}': ${result_host[$i]}";
done
final_result='true';
for i in "${!result_host[#]}"
do
if [[ `checkresult "${result_host[$i]}"` = 'true' ]]; then
final_result='false';
I am trying to executing the query on many different servers, with the following command
result_host[$i]=${PSQL_HOST[$i]}${sql_sel};
The above variables have the following meaning:
1. result_host[$i] : is an array that holds the i-th result of the sql query.
2. PSQL_HOST[$i] : is the command line psql-statement, including the IP address which is of the form
psql -t -q -h -U password -d database -c
3. $sql_sel : is the sql_statement
When I run the script, I get the following output.
scriptname.sh: line 168: SELECT: command not found
ERROR: syntax error at end of input
LINE 1: SELECT
^
Why is that? Any help, comments or suggestions would be appreciated.

Ksh function to query Oracle with return values

Some time ago I wrote a small routine to run some quick n' dirty queries (and with that I mean it is not used for large queries) against an Oracle DB, but also wanted to do it a bit easier to parse errors. Follows:
# Executes the query
#
# Will execute a query contained in the variable named
# in the parameter $4 and store the result in the variable
# named in $5.
# In case of errors (even SQL related) the function should
# exit with status 1, making it possible to "if execQuery".
#
# #param $1 = User
# $2 = Pasword
# $3 = Tns Alias
# $4 = Name of the variable containing the query
# $5 = Name of the variable to hold the result
#
# #return query execution status
function execQuery {
typeset eSQLU=$1
typeset eSQLP=$2
typeset eSQLS=$3
typeset etQUERY=$4
eval typeset eQUERY=\$$etQUERY
typeset eQRES=$5
logMessageFile "DEBUG" "Query: $eQUERY"
typeset res=$(sqlplus -s $eSQLU/$eSQLP#$eSQLS <<EOF
set echo off newpage 0 space 0 pagesize 0 feed off head off verify off lines 999
WHENEVER SQLERROR EXIT 1
$eQUERY
exit;
EOF
)
[[ $? -gt 0 ]] && return 1 || eval "$eQRES=\"$res\""
}
The idea of this function is that later I could do something like:
query="select sysdate from dual;"
if execQuery $RAID_APP_PI_USR $RAID_APP_PI_PWD $RAID_APP_PI_SID query result ; then
echo $result
logMessageFile "INFO" "Inserts into XX successful."
else
logMessageFile "ERROR" "Error insertando XXX."
fi
It kinda works... A properly written query will do it fine, and the result variable is all correctly evaluated and all. The problem are the errors. If the query in that example was something like select * potato potato;, It'd still not yield the correct return value thus missing the error test.
I'm not particularly good with sqlplus nor ksh, probably just missing something obvious... Could someone lend me a hand here?
Thanks!
I believe $? is returning the exit status of the typeset command, not the sqlplus command.
It may be easier to output the results of your SQLPLUS statement to a file instead of into a variable. Then you could either read that file with grep, looking for an "ORA-" message, or check the exit status variable.
sqlplus -s $eSQLU/$eSQLP#$eSQLS > querylog.tmp <<EOF
set echo off newpage 0 space 0 pagesize 0 feed off head off verify off lines 999
WHENEVER SQLERROR EXIT 1
$eQUERY
exit;
EOF
echo $?

Resources