1

I'm trying to write a bash script that will create a database using a variable for the new name but not having any luck with the syntax. I know almost next to nothing about bash. Keeps telling me there's a syntax error at line 1 after I enter the db password.

setup.sh

#!/bin/bash

db="mytest"

scl enable rh-mariadb 'mysql -u user -p -e "set @dbname=$db; \. setup_db.sql"'

setup_db.sql

SET @query = CONCAT('CREATE DATABASE `', @dbname, '`');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREAPRE stmt;

If I hardcode the db name where I have $db in the bash then I receive this error:

Unknown column 'mytest' in 'field list'

6
  • 1
    That error doesn't come from the CREATE DATABASE statement. You probably have some other statement in your setup_db.sql file that is malformed. Commented Aug 18, 2021 at 18:00
  • You should also look at the mysqladmin tool. You can create a schema more easily. Commented Aug 18, 2021 at 18:01
  • Doesn't this help? stackoverflow.com/questions/33470753/… Commented Aug 18, 2021 at 18:19
  • Or this one maybe. superuser.com/questions/288621/… Commented Aug 18, 2021 at 18:21
  • Second one doesn't use a variable. I saw the first one but no it hasn't helped. Commented Aug 18, 2021 at 18:27

1 Answer 1

1

You need to put the DB name in quotes in quotes, otherwise it's treated as a column name.

scl enable rh-mariadb 'mysql -u user -p -e "set @dbname=\"$db\"; \. setup_db.sql"'
Sign up to request clarification or add additional context in comments.

1 Comment

That fixed the error, but the variable is being received in the sql script as empty.

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.