How to pass a variable from a shell script to a mysql script

I have a bunch of mysql scripts that use name1 as the database name and populate that database with my data. However, I want to be able to choose the name of the database, instead of always naming it name1 everywhere in my sql scripts.

I already have a wrapper shell script that takes in the path of my data file and now I would like it to also take in the name of the database.

In my shell script, i assign:

DATABASE_NAME=$2

Is there any way at the top of my mysql scripts where I can use $DATABASE_NAME? So in the mysql scripts, it would be:

USE DATABASE_NAME;

instead of what I have right now:

USE name1;

Upvotes: 1

Views: 722

Answers (1)

Norbert
Norbert

Reputation: 6084

You can use mysql -e to execute your code:

mysql -e "USE ${DATABASENAME}; Some sql"

That way any replace works.

Optionally you can write temporary sql files or pipeline code into your mysql in which you just replace the ${DATABASENAME} when parsing that file. (The -e option is the most transparent and easiest)

Upvotes: 1

Related Questions