0

So I have this script:

#!/bin/bash

# Set the PostgreSQL database connection details
db_host="localhost"
db_port="5432"
db_name=""
db_user=""
db_password=""

# Function to execute psql command
psql_exec() {
    echo "Executing SQL query: $1"
    PGPASSWORD="$db_password" psql -h "$db_host" -p "$db_port" -d "$db_name" -U "$db_user" -c "$1"
    local exit_code=$?
    if [ $exit_code -ne 0 ]; then
        echo "SQL query exit code: $exit_code"
        return $exit_code
    fi
}

# Check for entry in database
user_id=$(psql_exec "SELECT user_id FROM users WHERE <condition>" -tAqx)
exit_code=$?
if [ $exit_code -ne 0 ]; then
    echo "SELECT user_id exit code: $exit_code"
fi

echo "value: $user_id"

The flags -tAqx aren't applied to the psql command. Therefore I got the wrong result instead of an empty response.

bash test.sh 
value: Executing SQL query: SELECT user_id FROM users WHERE <condition>;
 user_id 
---------
(0 rows)

The function will be used in different calls and therefore I don't want to add the flags directly to it. Obviously I could just write down the whole psql command with added flags just for this call, but I wonder if there is a smarter solution?

this solutions works but is not as clean as above: user_id=$(PGPASSWORD="$db_password" psql -h "$db_host" -p "$db_port" -d "$db_name" -U "$db_user" -c "SELECT user_id FROM users WHERE ;" -tAqx)

3
  • @rveerd thank you. I'll adapt this knowledge. I found my solution by removing the echo command, see above. Commented Apr 26, 2024 at 14:46
  • Do not edit answers into questions. Instead, add the answer as an answer below; clicking the checkbox next to that answer will mark the question solved (editing "solved" into titles is similarly against our rules). Commented Apr 26, 2024 at 15:14
  • As for "why" -- logs need to go to stderr, not stdout, to keep them separate from output. Put >&2 on any echo line intended to be information for users as opposed to output proper. Commented Apr 26, 2024 at 15:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.