而使用psql的shell脚本中存在全局变量作用域的循环问题



我正在从shell脚本中的psql获取数据并分配给全局变量,但全局变量没有更新,我已经尝试过:

#!/bin/bash
res_count=0
psql -h $db_host -U $db_user -d $db_name -At -c "select count(id) as dCount from abc" --no-password --field-separator ' ' | 
while read dCount ; do
res_count=$dCount
done;
echo $res_count

$res_count没有更新,它仍然值为0,请纠正我的错误,谢谢

while循环在子shell中执行,因为它是作为管道的一部分执行的。您可以通过使用lastpipe或将psql命令放置在进程替换中来避免它。

#/bin/bash
shopt -s lastpipe
...

res_count=0
while read dCount ; do
res_count=$dCount
done < <(psql -h "$db_host" -U "$db_user" -d "$db_name" -At 
-c "select count(id) as dCount from abc" 
--no-password --field-separator ' ')
echo "$res_count"

附带说明一下,正确引用变量。

最新更新