Passing IFS values to a dynamic array
-
25-07-2021 - |
Question
i have a Oracle output (select output) as cand1 cand2 cand3 cand62 now i need to store these values in an array through shell script.
#!/bin/bash
instant_client="/root/ora_client/instantclient_11_2"
output=`$instant_client/sqlplus -s HRUSER/HRUSER@TOMLWF <<EOF
set heading off
set feedback off
set lines 10000
set pagesize 10000
select count (1) from onboardingcandidates o, candidatedetails c where o.candidateid=c.candidateid and o.JOININGSTATUS='0091' and to_date(o.joiningdate)=to_date(sysdate+5);
EOF
exit
query=`$instant_client/sqlplus -s HRUSER/HRUSER@TOMLWF <<EOF
set heading off
set feedback off
set lines 10000
set pagesize 10000
select o.candidateid from onboardingcandidates o, candidatedetails c where o.candidateid=c.candidateid and o.JOININGSTATUS='0091' and to_date(o.joiningdate)=to_date(sysdate+5);
EOF
exit
i=0
echo "Throwing individual arrays:"
while [ $i -le $output ]
do
a=${query[$i]}
echo Candidate[$i]=$a
i=$(($i+1))
done
OUTPUT IS
Throwing individual arrays:
Candidate[0]= cand1 cand2 cand3 cand62
Candidate[1]=
Candidate[2]=
Candidate[3]=
Candidate[4]=
REQUIRED OUTPUT
Throwing individual arrays:
Candidate[0]= cand1
Candidate[1]= cand2
Candidate[2]= cand3
Candidate[3]= cand62
Solution
The problem is that query
is a string, not an array, so ${query[$i]}
does not work as you expect.
In general, to convert a string to an array you would do this:
$ string="foo bar"
$ array=($string)
$ echo ${array[0]}
foo
$ echo ${array[1]}
bar
In your case, if you surround the sqlplus
command with parentheses, the output will be stored in an array. Like this:
query=(`$instant_client/sqlplus -s HRUSER/HRUSER@TOMLWF <<EOF
set heading off
set feedback off
set lines 10000
set pagesize 10000
select o.candidateid from onboardingcandidates o, candidatedetails c where o.candidateid=c.candidateid and o.JOININGSTATUS='0091' and to_date(o.joiningdate)=to_date(sysdate+5);
EOF)
And then you can access elements in the query
array using an index: ${query[$i]}
OTHER TIPS
Something like this:
$ query="cand1 cand2 cand3 cand62"
$ read -a Candidate <<<$query
$ echo ${Candidate[0]}
cand1
$ echo ${Candidate[1]}
cand2
When you are out of your sqlplus, your "query" variable contains something like above. By simply reading the entire thing into an array as shown above, you can access the values.