linux - shell 脚本 : Count returned from function is not correct

标签 linux shell unix

在下面的 shell 脚本中,我连接到数据库并获取计数值。 在下面的代码中,我没有得到正确的计数值。相反,它返回 185(随机 int 值) 但应该返回的实际计数值是 2233。 如果我将 return 替换为 echo,它会打印出正确的 2233 值。但是 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 

//如果使用返回,则打印 185。如果使用 echo,则打印 0。

最佳答案

使用 printf 并在您的函数中检索“count”的最终值作为标准输出。

#!/bin/sh


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

alertCount=$(findAlertCount)

printf "alertCount $alertCount\n"

此外,我观察到您正在使用括号 () 将函数体作为子 shell 调用。如果目的只是将命令描述为一个集合或列表,则可以尝试使用方括号 {},以便程序的其余部分可以访问 count 的值。

关于linux - shell 脚本 : Count returned from function is not correct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32922589/

相关文章:

unix - 迎接2038年我们应该做什么准备?

PHP chmod() 无法在服务器上运行

c - 在 Linux 中设置 FD 标志

java - 从 Java 运行 python 脚本时找不到 mvn 命令

linux - 在fish shell中定义别名

linux - ext3cow 还在开发中吗?

linux - 树莓派重置我的服务器

c++ - 为什么CMake通过相对路径链接外部库?

Python:打包时出错

shell - 逐行读取并写入另一个文件shell脚本