If loop not working properly - bash

In my script i execute correctly when first time in the if loop execute after the third time of execution its not working properly .what can i do is any mistake ah...? please fix my issue...?in the script i gave the value for customer name as ABC then again i gave the ABC that time it ececute the if condition correctly,but i gave the third time as ABC its not working properly..!
#!/bin/bash
echo " --- Enter the Database name ---"
read databasename
echo " --- enter the table name --- "
read table_name
sqlite3 $databasename.db "DROP TABLE IF EXISTS $table_name;"
sqlite3 $databasename.db "CREATE TABLE IF NOT EXISTS $table_name(cus_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,cus_name TEXT NOT NULL UNIQUE ,cus_domain TEXT UNIQUE, cus_status TEXT NOT NULL,Port INTEGER NOT NULL);"
echo " --- Enter the total number of rows do you want ---"
read cus_count
echo "--- Enter the following details one by one---"
port_num=8080
for((i=1;i<=cus_count;i++))
do
echo "enter the $i customer details"
echo "---Enter the customer name---"
read c_name
customer=$(sqlite3 $databasename.db "select cus_name from $table_name")
if [[ "$port_num" == "$port_num" ]]; then
port_num=$(($port_num + 1))
fi
if [[ $c_name != $customer ]]
then
echo "---Enter the Status(Active/Inactive)---"
read c_status
c_domain="$c_name"
else
echo "---OOPS you entered customer name already available---"
echo "---Please enter new customer name---"
i=$(($i - 1))
fi
sqlite3 $databasename.db "INSERT OR IGNORE INTO $table_name (cus_name,cus_domain,cus_status, Port) VALUES(\"$c_name\",\"${c_domain,,}.com\",\"$c_status\",\"$port_num\") ;"
done
echo " --- Records from the $table_name ---"
sqlite3 $databasename.db "select * from $table_name;"

please refer to below on "bash script arithmetic operations"
http://tldp.org/LDP/abs/html/arithexp.html
or
http://tldp.org/LDP/abs/html/ops.html

Related

Query returns 0, but my conditional statement isn't recognizing it as a 0

My Bash script uses SQLite to store data. I'm comparing id's (column jid) from table tester for which id's are in table test2:
sqlite3 jail.db "SELECT jid FROM tester" | while read jid; do
if sqlite3 jail.db "select exists(select 1 from test2 where jid=$jid limit 1)"; then
echo "i found it"
else
echo "i did not find it"
fi
done
Going through id's query returns 0 or 1, but my Bash script executes the 1 part of If/then/else regardless:
0
i found it
0
i found it
0
i found it
0
i found it
1
i found it
1
i found it
1
i found it
I guess you are looking for a left outer join, something like this
for r in $(sqlite3 jail.db 'select case when test2.jid != "" then 1 else 0 end from tester left outer join test2 on tester.jid = test2.jid;'); do
if [[ "$r" == 1 ]]; then
echo "i found it"
else
echo "i did not find it"
fi
done
notice the use of $() to get the output of the command not its exit value.

Shell Script piping

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

script weird behaviour with ampersand at end

I am writing a script where I face a very strange problem.
My script is :
#!/bin/bash
set -x
cd /scripts/my-scripts
echo "Getting data from database."
mysql -N -umyuser -pmypass -hdb.test.example.com COLLEGE -e"select distinct id as myid from candidate_info where name = 'john' and id is not null " > test_skus &
echo "DONE"
echo `wc -l test_skus`
It gives 0 as word count. But if I remove & at end of this :
mysql -N -umyuser -pmypass -hdb.test.example.com COLLEGE -e"select distinct id as myid from candidate_info where name = 'john' and id is not null " > test_skus &
It give results. What can be the reason ? Please help

BASH, passing variables to a string for sqlite

Ive hit a dead end trying to pass variables created in bash to a sqlite command string.Below you can see I am trying to write the artist_id (foreign key) into the songs table in artist_id. I can retrieve th artist_id field fine from the artists table. When I try to create a new record in the songs table with the variable $artist_id, I get an error;
Error: FOREIGN KEY constraint failed
Its definitely the correct key, 4 in this case, but sqlite doesn't seem to be accepting it so I think it may be a formatting issue? I tried removing quotes, adding '..etc. but no joy, any ideas?
artistcheck=$(sqlite3 "$dbFile" "$forkey SELECT EXISTS(SELECT 1 FROM artists WHERE artist_name='${ARRAY[2]}' LIMIT 1);")
if [ "$artistcheck" -eq 1 ]; then
artistid=$(sqlite3 "$dbFile" "$forkey SELECT artist_id FROM artists WHERE artist_name='${ARRAY[2]}';")
echo "Yep, "${ARRAY[2]}" exists and the id is $artistid."
else
echo "Nope, "${ARRAY[2]}" doesnt exist"
sqlite3 "$dbFile" "$forkey INSERT INTO artists (artist_name) VALUES ('${ARRAY[2]}');"
artistid=$(sqlite3 "$dbFile" "$forkey SELECT artist_id FROM artists WHERE artist_name='${ARRAY[2]}';")
echo "New Artist created. Name: ${ARRAY[2]} and ID is $artistid."
fi
songcheck=$(sqlite3 "$dbFile" "$forkey SELECT EXISTS(SELECT 1 FROM songs WHERE song_name='${ARRAY[1]}' AND artist_id='$artistid' LIMIT 1);")
if [ "$songcheck" -eq 1 ]; then
songid=$(sqlite3 "$dbFile" "$forkey SELECT song_id FROM songs WHERE song_name='${ARRAY[1]}' AND artist_id='$artistid';")
echo "Yep, "${ARRAY[1]}" exists and the song ID is $songid and the artist id is $artistid."
else
echo "Nope, "${ARRAY[1]}" doesnt exist"
sqlite3 "$dbFile" "$forkey INSERT INTO songs (artist_id, song_name) VALUES ('$artist_id','${ARRAY[2]}');"
songid=$(sqlite3 "$dbFile" "$forkey SELECT song_id FROM songs WHERE song_name='${ARRAY[1]}' AND artist_id='$artist_id';")
echo "New Song created. Name: ${ARRAY[1]} and song ID is $songid and the artist id is $artistid."
fi
Mixed up the variable $artistid with the field 'artist_id' in the sql statement. 4th line from the bottom I believe. Moral: use meaningful variable names and lay off the caffeine.

Update oracle table with start and end times from shell script

There are three materialized views being refreshed in a single shell script(.ksh) and I am trying to insert the start, end timestamps for each MV in a oracle table(created for audit purpose). I tried creating a .sql file with insert statement that is being called at end of each refresh but unable to get the intended result. This is the first time I am working on shell script, can anyone please help me?
Thanks and Regards
Kiran.
CODE:
typeset -Z6 i
i=0
echo $PROP_FILE
VIEWS=$(echo $viewset| tr "," " ")
for VIEW in $VIEWS
do
echo "Generating $XML_FILE"
echo " "
echo "Start Refresh view: ${VIEW} at : $(date)"
if [ $DB_READ_FLAG -eq 0 ]
then
echo "calling launch_sqlplus.ksh "
#YRV
#Adding below line fix the defect 7494
#$BIN/launch_sqlplus.ksh $SQL/exports_refresh_view.sql $VIEW \
#$BIN/launch_sqlplus.ksh $SQL/exports_refresh_view.sql $VIEW || exit_with_error
else
echo "calling launch_sqlplus_read."
#YRV
#Adding below line fix the defect 7494
#$BIN/launch_sqlplus_read.ksh $SQL/exports_refresh_view.sql $VIEW \
# $BIN/launch_sqlplus_read.ksh $SQL/exports_refresh_view.sql $VIEW || exit_with_error
fi
echo "End Refresh view: ${VIEW} at : $(date)\n"
LOG FILE:
Start Refresh view: mv_lt_port_config at : Wed Aug 27 20:09:34 METDST
2014 calling launch_sqlplus_read.
Loading /isii/isi/bin/isi_profile_read isii
Launch SQL-script with paramaters :
/isii/isi/sql/exports_refresh_view.sql mv_lt_port_config
Session altered.
Session altered.
Session altered.
Session altered.
old 1: ALTER SESSION SET tracefile_identifier=mv_refresh_&1 new 1:
ALTER SESSION SET tracefile_identifier=mv_refresh_mv_lt_port_config
Session altered.
Session altered.
Session altered.
old 2: xml_report.refresh_mview('&1'); new 2:
xml_report.refresh_mview('mv_lt_port_config');
PL/SQL procedure successfully completed.
End Refresh view: mv_lt_port_config at : Wed Aug 27 20:12:17 METDST
2014
This answer may be partial, because of incomplete code in the question, however values can be inserted into a DB table from a ksh script as follows:
Assuming a DB Table is created -
CREATE TABLE VIEW_REFRESH_LOG
(OPERATION VARCHAR2(60),
START_DATE DATE,
END_DATE DATE);
Then the following sql file can be created -
REM ----------- insertRecord.sql -------------------------------
DEFINE DATEFORMAT = 'DD-MM-YYYY HH24:MI:SS'
DEFINE OPERATION = &1
DEFINE STARTING = '&2 &3'
DEFINE ENDING = '&4 &5'
INSERT INTO refresh_log
( operation,
start_time,
end_time)
VALUES
('&OPERATION',
to_date('&STARTING','&DATEFORMAT'),
to_date('&ENDING','&DATEFORMAT'));
COMMIT;
EXIT SUCCESS;
then, in the shell script -
...
CREDENTIALS="oracle_user/oracle_pass"
echo "Start Refresh view: ${VIEW} at : $(date)"
if [ $DB_READ_FLAG -eq 0 ]
then
echo "calling launch_sqlplus.ksh "
#YRV
#Adding below line fix the defect 7494
STARTDATE=$(date '+%d-%m-%Y')
STARTTIME=$(date '+%H:%M:%S')
#$BIN/launch_sqlplus.ksh $SQL/exports_refresh_view.sql $VIEW \
$BIN/launch_sqlplus.ksh $SQL/exports_refresh_view.sql $VIEW || exit_with_error
ENDDATE=$(date '+%d-%m-%Y')
ENDTIME=$(date '+%H:%M:%S')
PARAMETERS="'launch_sqlplus ${VIEW}' '${STARTDATE}' '${STARTTIME}' '${ENDDATE}' '${ENDTIME}'"
sqlplus -S $CREDENTIALS #insertRecord.sql "$PARAMETERS"
else
echo "calling launch_sqlplus_read."
#YRV
#Adding below line fix the defect 7494
STARTDATE=$(date '+%d-%m-%Y')
STARTTIME=$(date '+%H:%M:%S')
#$BIN/launch_sqlplus_read.ksh $SQL/exports_refresh_view.sql $VIEW \
$BIN/launch_sqlplus_read.ksh $SQL/exports_refresh_view.sql $VIEW || exit_with_error
ENDDATE=$(date '+%d-%m-%Y')
ENDTIME=$(date '+%H:%M:%S')
PARAMETERS="'launch_sqlplus_read ${VIEW}' '${STARTDATE}' '${STARTTIME}' '${ENDDATE}' '${ENDTIME}'"
sqlplus -S $CREDENTIALS #insertRecord.sql "$PARAMETERS"
fi
echo "End Refresh view: ${VIEW} at : $(date)\n"
That would derive the start and end time of the operation you're performing, and pass it as parameters to SQL*Plus, which takes those parameters and inserts them as bind variables into the sql script.
You need to be wary of the quotes when passing strings as parameters to SQL*Plus. Also, you'd want to modify your DATEFORMAT to whatever your value is for NLS_DATE_FORMAT.
Hopefully that addresses your question. If not, please clarify further.

Resources