将IFS值传递给动态数组

时间:2012-11-01 11:04:26

标签: shell scripting scripting-language

我有一个Oracle输出(选择输出)作为cand1 cand2 cand3 cand62 现在我需要通过shell脚本将这些值存储在一个数组中。

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

输出

Throwing individual arrays:

    Candidate[0]= cand1 cand2 cand3 cand62
    Candidate[1]=
    Candidate[2]=
    Candidate[3]=
    Candidate[4]=

需要的输出

Throwing individual arrays:

    Candidate[0]= cand1   
    Candidate[1]= cand2
    Candidate[2]= cand3
    Candidate[3]= cand62

2 个答案:

答案 0 :(得分:2)

这样的事情:

$ query="cand1 cand2 cand3 cand62"
$ read -a Candidate <<<$query
$ echo ${Candidate[0]}
cand1
$ echo ${Candidate[1]}
cand2

当你离开sqlplus时,你的“查询”变量包含类似上面的内容。通过简单地将整个事物读入如上所示的数组,您可以访问值。

答案 1 :(得分:2)

问题是query是一个字符串,而不是一个数组,所以${query[$i]}不能按预期工作。

通常,要将字符串转换为数组,您可以这样做:

$ string="foo bar"
$ array=($string)
$ echo ${array[0]}
foo
$ echo ${array[1]}
bar

在您的情况下,如果用括号括起sqlplus命令,则输出将存储在数组中。像这样:

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)

然后您可以使用索引访问query数组中的元素:${query[$i]}