【问题标题】:query return null in bash for psql查询在 bash 中为 psql 返回 null
【发布时间】:2021-02-23 19:43:43
【问题描述】:

我想在 bash 脚本中获取某个表中记录的计数,但返回时 $num 为空(应该是数字)。当我直接在pgadmin中运行时查询是正确的,我可以获得行数。有谁知道怎么回事?

declare -a ROW=($(psql \
        -X \
        -U $DB_USER \
        -h $DB_HOST \
        -d $DB_NAME \
        -p $DB_PORT \
        --set ON_ERROR_STOP=on \
        --no-align \
        -t \
        --field-separator ' ' \
        --quiet \
        -c "SELECT count(*) as num
            FROM table_test)")
    )
    
    echo "num_error: $num  here"
    if [[ $num == 0 ]]; then
        echo "no error occur within the past 1 hour"
    elif [[ $num == '' ]]; then
        echo "return nothing"
    else echo "$num"
    fi

【问题讨论】:

  • 您将输出分配给ROW,然后您检查$num...
  • num 是 SQL 变量,而不是 shell 变量。

标签: bash psql


【解决方案1】:

SQL 别名不会成为 shell 变量,因此在查询中使用 AS num 不会在 shell 中设置 $num

查询的输出被放入ROW 数组中,因此您可以从${ROW[0]} 中获取您想要的值。如果查询只返回一个值,也不需要使用数组。所以你可以这样做:

num=$(psql \
        -X \
        -U $DB_USER \
        -h $DB_HOST \
        -d $DB_NAME \
        -p $DB_PORT \
        --set ON_ERROR_STOP=on \
        --no-align \
        -t \
        --field-separator ' ' \
        --quiet \
        -c "SELECT count(*)
            FROM table_test)")
    )

【讨论】:

  • 嗨 Barmar,谢谢,我实际上测试了这段代码,而且 declare -a ROW=($(psql \ -X \ -U $DB_USER \ -h $DB_HOST \ -d $DB_NAME \ -p $DB_PORT \ --set ON_ERROR_STOP=on \ --no-align \ -t \ --field-separator ' ' \ --quiet \ -c "SELECT count(*) as num FROM table_test)") ) num_error=${ROW[0]} echo "numtest_error: $num_error here" 它仍然给我返回空答案...
猜你喜欢
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
相关资源
最近更新 更多