user2488578
user2488578

Reputation: 916

Shell script : Count returned from function is not correct

In the below shell script I am connecting to DB and getting the count value. In the below code I am not getting the correct count value. Instead it is returning 185 (random int value) but the actual count value which is supposed to be returned is 2233. If I replace return with echo, it prints the correct 2233 value. But alertCount variable is assigned 0 value.

findAlertCount(){
(
count=$(sqlplus -s  ${DBA_ORACLE_USER}/${DBA_ORACLE_PWORD}@${ORACLE_SID} <<END
#connect ${DBA_ORACLE_USER}/${DBA_ORACLE_PWORD}@${ORACLE_SID}
set serveroutput on
set linesize 1000
set heading off
set feedback off
SELECT count(1)
FROM mytable
WHERE mycolumn IS NOT NULL;
exit;
END
)
return "$count"
)
}

findAlertCount
alertCount=$?
echo "alertCount" $alertCount 

//This prints 185 if return is used. And prints 0 if echo is used.

Upvotes: 1

Views: 701

Answers (2)

Stig Brautaset
Stig Brautaset

Reputation: 2632

When in doubt, simplify. And use set -x to see what's going on. Here I'm replacing your SQL command with a simple echo to simulate your SQL (because I don't have access to Oracle):

set -x
findAlertCount(){
(
    count=$(echo 2233)
    return "$count"
)
}

findAlertCount
alertCount=$?
echo "alertCount" $alertCount

When run, that prints:

+ findAlertCount
++ echo 2233
+ count=2233
+ return 2233
+ alertCount=185
+ echo alertCount 185
alertCount 185

However, rewriting it slightly to this:

set -x
findAlertCount(){
    count=$(echo 2233)
    echo "$count"
}

alertCount=$(findAlertCount)
echo "alertCount" $alertCount

and running it we get the expected result:

++ findAlertCount
+++ echo 2233
++ count=2233
++ echo 2233
+ alertCount=2233
+ echo alertCount 2233
alertCount 2233

Upvotes: 1

user4832408
user4832408

Reputation:

Use printf and retrieve the final value of "count" in your function as stdout.

#!/bin/sh


findAlertCount()
{
    count=2233
    printf "$count"
}

alertCount=$(findAlertCount)

printf "alertCount $alertCount\n"

Additionally I observe you are using parenthesis () to invoke the body of the function as a subshell. If the intent is merely to delineate the commands as a set or list perhaps try brackets {} instead so the value of count is accessible to the rest of the program.

Upvotes: 3

Related Questions