我正在从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"
附带说明一下,正确引用变量。