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)
>&2on anyecholine intended to be information for users as opposed to output proper.