1

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.

2
  • Don't use the return value of a function to pass data. It is solely for indicating if the function has succeeded or failed. Commented Oct 3, 2015 at 15:53
  • There's a very good answer on how to return from a shell function here: stackoverflow.com/a/8743103/5950 Commented Oct 5, 2015 at 18:15

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good point about the subshell but I don't really see the advantage of making the variable global - if anything, I'd suggest using local to reduce its scope.
local is not part of POSIX; the user may not be using bash.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.