0

In a Bash script I need to execute a command which takes the list of the existing databases from PostgreSQL:

getdblist_cmd=(sudo -u $backup_user $psql -p $pgsql_port -U $pgsql_user -d postgres -q -t -c 'SELECT datname from pg_database')

# Get databases list
msg
msg "================================================================="
msg "Getting databases list ..."
dblist=`"${getdblist_cmd[@]}"`
status=$?
if [ "$status" -ne "0" ]; then
    return $status
fi

This works but I need to exclude the template0 database, but this does not work:

getdblist_cmd=(sudo -u $backup_user $psql -p $pgsql_port -U $pgsql_user -d postgres -q -t -c 'SELECT datname from pg_database WHERE datname != \'template0\')'

# Get databases list
msg
msg "================================================================="
msg "Getting databases list ..."
dblist=`"${getdblist_cmd[@]}"`
status=$?
if [ "$status" -ne "0" ]; then
    return $status
fi

It returns:

root@postgres /u/l/sbin# ./pgsql-backup-full-func.sh
./pgsql-backup-full-func.sh: line 145: unexpected EOF while looking for matching `''
./pgsql-backup-full-func.sh: line 187: syntax error: unexpected end of file

I know that no escaping is possible for single quotes in Bash, so how I can manage this?

1
  • Did you forget the opening single quote ' in your second copy of the script to stackoverflow? I feel like a single quote is missing before SELECT... Commented Feb 25, 2020 at 14:23

2 Answers 2

1

Stop using arrays when you should be using functions.

getdblist_cmd () {
  sudo -u "$backup_user" "$psql" -p "$pgsql_port" -U "$pgsql_user" -d postgres -q -t -c "SELECT datname from pg_database WHERE datname != 'template0'"
}

# Get databases list
msg
msg "================================================================="
msg "Getting databases list ..."
dblist=$(getdblist_cmd)
status=$?
if [ "$status" -ne "0" ]; then
    return $status
fi
Sign up to request clarification or add additional context in comments.

Comments

0

I guess you have a few options --

Using double quotes

getdblist_cmd=(sudo -u $backup_user $psql -p $pgsql_port -U $pgsql_user -d postgres -q -t -c "SELECT datname from pg_database WHERE datname != 'template0'")

Using one more variable

sql_query='SELECT datname from pg_database WHERE datname != '\''template0'\'
getdblist_cmd=(sudo -u $backup_user $psql -p $pgsql_port -U $pgsql_user -d postgres -q -t -c $sql_query)

1 Comment

Yes, you cannot put a single quote in a single quoted string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.