1

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

lazyCoder
  • 2,544
  • 3
  • 22
  • 41

1 Answers1

2

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.

konsolebox
  • 72,135
  • 12
  • 99
  • 105