1

I'm kind of new in bash script and postgresql.

I saw in another question a way to run a bash script as psql user here.

I tried making a bash function as follow,

postgres_create_db(){
sudo su postgres <<- EOF
    if psql -lqt | cut -d \| -f 1 | grep -qw nokia_aaa_poc_db; then
        psql -c '\dt'
    else
        psql -c 'CREATE DATABASE nokia_AAA_poc_db;' 
    fi
EOF
exit
}

where this function will be called further in code, but I wonder if I can add a RETURN to the function that's actualy returning a varible that was first declared inside postgres bash (in between the EOF's). Like bellow:

postgres_create_db(){
    sudo su postgres <<- EOF
        if psql -lqt | cut -d \| -f 1 | grep -qw nokia_aaa_poc_db; then
            psql -c '\dt'
            exists=1 #where thats a variable that I want to access outside the postgres bash.
        else
            psql -c 'CREATE DATABASE nokia_AAA_poc_db;' 
        fi
    EOF
    exit

    return exists
}

but it gives an error on shellcheck

return exists
               ^-- SC2152: Can only return 0-255. Other data should be written to stdout.
Hugo Abreu
  • 109
  • 1
  • 7

1 Answers1

2

Functions in bash can only return values from 0 to 255 where 0 is success. Reference: Return value in a Bash function

So you can echo the variable like this instead:

#!/usr/bin/env bash

postgres_test() {
    psql -c '\dt' &> /dev/null
    declare exists=1
    echo $exists
}

printf "%s\n" "$(postgres_test)"

This prints "1".
You'll also notice that I redirected the output of the Postgres command to /dev/null. This is because it would be combined in the function's output otherwise.
You might wish to redirect that output to a file instead.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • Hi, thank you for the response, but let me check if I understood it right, the exists variable is declare inside de postgres command? My problem is that I want to take out an variable that was declare inside the here document in the postgres bash. – Hugo Abreu Jan 22 '20 at 17:19