Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

#!/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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your while loop executes in a subshell because it is executed as part of the pipeline. You can avoid it by using lastpipe or placing the psql command inside process substitution.

#/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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading