Home  >  Q&A  >  body text

Mysql bash database name is wrong when database exists?

I am currently scripting the migration using bash scripting. When I try to open the database via a variable in a bash script, the database name is incorrect. I get the following error "'RROR 1102 (42000): Database name 'development' is incorrect"

mysql --batch --host=********** --user=**** --password=***** $dbName -e "${fileContents}"

When I do this in a bash script, the database exists

mysql --batch --host=********** --user=**** --password=***** development -e "${fileContents}"

The variable fileContents is the migration script in SQL. The variable dbName is the name of the database.

I get the database name from a table in the database with the following lines

databaseNames=()
shopt -s lastpipe
mysql --batch --raw  --host=***** --user=**** --password=***** -e 'SELECT database_name FROM users.organisations'  | while read dbName guid; do
    if [ $i -gt 0 ]
    then
        databaseNames+=($dbName)
    fi
    i=$(($i + 1))
done

The names in the database array seem to be correct, but I think the array is messing things up. I'm looping over the true array as follows.

for dbName in "${databaseNames[@]}" do

P粉818125805P粉818125805264 days ago386

reply all(1)I'll reply

  • P粉714844743

    P粉7148447432024-01-30 10:57:21

    Your array is empty. You have to change the while loop to

    while read dbName guid; do
          databaseNames+=($dbName)
    done < <(mysql --batch --raw  --host=$host --port=$port --user=$user --password=$password  --database="yourdatabase" -e 'SELECT database_name FROM users.organisations;')

    Then

    for dbName in "${databaseNames[@]}"
    do
      echo $dbName
      mysql --batch --raw  --host=$host --port=$port --user=$user --password=$password  --database="$dbName" -e '${fileContents};')
    done

    reply
    0
  • Cancelreply