Sparky1
Sparky1

Reputation: 35

BASH - execute mysql commands using arguments stored in an array

I have my WordPress database name, username and password stored in an array and I'm trying to have the script connect to the database and display the home/site_url field from the table wp-options.

Array defined. Information is read from a file.

var1=$(<dbinfo2.temp)
arr=($var1)

Array works example:

echo "${arr[0]}"
echo "${arr[2]}"

: Output:

pinkywp_wrdp1
Mq2uMCLuGvfyz

But the below code doesn't work for some reason.

OUTPUT="$(mysql -u ${arr[1]} -p ${arr[2]} -D ${arr[0]} -e "SELECT home FROM wp_options")"
echo "${OUTPUT}"

I keep getting the following error even though the database username/password stored in the array are correct. It's like as if mysql isn't seeing the password I'm passing to it.

This is a on a CentOS/cPanel server running MySQL and Apache.

Warning: Using unique option prefix pass instead of password is deprecated and will be removed in a future release. Please use the full name instead.
Enter password: 
ERROR 1045 (28000): Access denied for user 'pinkywp_wrdp1'@'localhost' (using password: NO)

I'd forever be grateful if you could please tell me what I'm doing wrong and how I can get this to connect and pull the information I need.

Many thanks!

Upvotes: 1

Views: 124

Answers (2)

sKwa
sKwa

Reputation: 889

Comments are limited, so I will post it as answer. Try:

#!/bin/bash
#
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicated.
# Flat is better than nested.
# Sparse is better than dense.
# Readability counts.

CONFIG=( $(<dbinfo2.temp ) )

# check that everythink is ok(no spaces - its ok)
DBNAME="-D${CONFIG[0]}"
DBUSER="-u${CONFIG[1]}"
DBPSWD="-p${CONFIG[2]}"

# query db
OUTPUT=$(mysql "${DBNAME}" "${DBUSER}" "${DBPSWD}" -e 'SELECT 1')

# check ouput, should be: 1 1
echo "${OUTPUT}"

exit 0

Try to run it and if it fails please add set -x option after shebang, run it and post full output from console.

#!/bin/bash
set -x
...

Upvotes: 2

Sparky1
Sparky1

Reputation: 35

Turns out the issue was syntax because of the usage of both " " and $() for populating the variable from the array. This worked fine:

OUTPUT=$(mysql -ss -u ${arr[1]} -p${arr[2]} -D ${arr[0]} -e "SELECT option_value FROM wp_options WHERE option_name='home'" 2>/dev/null) 
echo $OUTPUT

Upvotes: 0

Related Questions