[英]while loop with global variable scope issue in shell script with psql
I am fetching the data from psql in the shell script and assign to the global variable but the global variable is not updating below i have tried:我正在从 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 is not updating, it has still value 0, please correct me where i am wrong thanks $res_count 没有更新,它的值仍然为 0,请纠正我的错误,谢谢
Your while
loop executes in a subshell because it is executed as part of the pipeline.您的while
循环在子 shell 中执行,因为它是作为管道的一部分执行的。 You can avoid it by using lastpipe
or placing the psql
command inside process substitution.您可以通过使用lastpipe
或将psql
命令放在进程替换中来避免它。
#/bin/bash
shopt -s lastpipe
...
Or或者
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"
As a side note, quote your variables properly.作为旁注,请正确引用您的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.