简体   繁体   English

Shell脚本:从函数返回的计数不正确

[英]Shell script : Count returned from function is not correct

In the below shell script I am connecting to DB and getting the count value. 在下面的shell脚本中,我将连接到DB并获取计数值。 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. 相反,它返回185(随机int值),但是应该返回的实际计数值为2233。如果我将return替换为echo ,则会打印正确的2233值。 But alertCount variable is assigned 0 value. 但是alertCount变量被分配了0值。

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. //如果使用return,则输出185。 And prints 0 if echo is used. 如果使用echo,则输出0。

Use printf and retrieve the final value of "count" in your function as stdout. 使用printf并在函数中以stdout检索“ count”的最终值。

#!/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. 如果仅是将命令描述为一组或列表,则可以尝试使用括号{}以便其余部分可以访问count的值。

When in doubt, simplify. 如有疑问,请简化。 And use set -x to see what's going on. 并使用set -x查看发生了什么。 Here I'm replacing your SQL command with a simple echo to simulate your SQL (because I don't have access to Oracle): 在这里,我用简单的回显替换您的SQL命令以模拟您的SQL(因为我无权访问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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM