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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.