我正在從 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,請糾正我的錯誤,謝謝
uj5u.com熱心網友回復:
您的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"
作為旁注,請正確參考您的變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/406197.html
標籤:
上一篇:使用bash過濾行
