need to "build" a mysql command and exec it in a shell script - mysql

I'm new to writing shell scripts.
I am attempting to create a database using a shell script. Here's the script:
#!/bin/bash
#create a new db
a="mysql -uuser -ppassword -e'create database $1;'"
exec $a
The command exec mysql -uuser -ppassword -e'create database databaseName;' works in a shell, but when I sh the script, I get the mysql help open...

I think the problem is in the quotes, the simple quote prevent the variable expansion.
You can simply do like this in your script:
#!/bin/bash
#create a new db
mysql -u user -p password -e "create database $1;"
Or you can try to place all your mysql commands in a file, let's say "dbname.sql".
And do this:
#!/bin/bash
#create a new db
mysql -u user -p password "$1" < "$1.sql"

if you like use exec to run commands this can be a possible solution
#!/bin/bash
#create a new db
programm="mysql"
parameter[0]="-ppassword"
parameter[1]="-uuser"
parameter[2]="-ecreate database $1;"
exec "$programm" "${parameter[#]}"
exec parameter are
exec [-a NAME] [-cl] [COMMAND] [ARG...] [REDIRECTION...]
command is $programm and the array parameter is the argument list.

Sounds like you need to use the 'cat' command and a pipe instead of using 'exec' .
cat /path/to/my/file | mysql -h localhost -u root -padmin

Related

Exporting views from Mysql using Docker commmand

The code below extracts views separately from the database. However, I'm trying to get this to run in a single docker run or exec command.
Right now when I try, the pipe command and in combination with trying to escape quotes gives me errors.
mysql -u username INFORMATION_SCHEMA
--skip-column-names --batch
-e "select table_name from tables where table_type = 'VIEW'
and table_schema = 'database'"
| xargs mysqldump -u username database
> views.sql
Anyone know how to achieve this within one docker command?
For example:
docker exec -i $(docker-compose ps -q mysqldb) mysql ...
Much love.
You can run both the mysql client command and the mysqldump tool from somewhere that's not "on the database server". In your case, you can run them from the host that has the MySQL server, assuming you launched the database with options like docker run -p 3306:3306. It would look something like
mysql -h 127.0.0.1 -u username INFORMATION_SCHEMA \
--skip-column-names --batch \
-e "select table_name from tables where table_type = 'VIEW' and table_schema = 'database'" \
| xargs mysqldump -h 127.0.0.1 -u username database \
> views.sql
This avoids all of the shell quoting problems trying to feed this into docker exec, and also avoids the requirement to need root-level access on the host to do an administrative task (if you can run any Docker command at all then you can use docker run to add yourself to the host's /etc/sudoers, among other things).
I also agree with #MichaelBoesl's answer, though: this is long enough that trying to make it into a one-liner isn't really worth the trouble that the various quoting and escaping will bring. I'd probably write this into a script and put the SQL query into a file.
#!/bin/sh
: ${MYSQL_HOST:=127.0.0.1}
: ${MYSQL_USER:=username}
: ${MYSQL_DATABASE:=INFORMATION_SCHEMA}
cat >/tmp/dump_views.sql <<SQL
SELECT table_name
FROM tables
WHERE table_type='VIEW' AND table_schema='database';
SQL
mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" --skip-column-names --batch \
"$MYSQL_DATABASE" </tmp/dump_views.sql \
| xargs mysqldump -h "$MYSQL_HOST" -u "$MYSQL_USER" "$MYSQL_DATABASE"
You can put all your commands into a bash script on the container and just execute the script!

Using batch variable in sqlcmd query

I'm trying to create a batch to execute a few sql script and some queries. I use sqlcmd in my batch like this :
#echo off
sqlcmd -S server -U user -P password -Q query
As I will execute different queries on the same server, I'd like to replace the server statement with a variable. So I could write something like this :
#echo off
SET server=192.X.X.X
sqlcmd -S server -U user -P password -Q first query
sqlcmd -S server -U user -P password -Q second query
I found this question on SO but I'm still unable to understand how that works :
SQLCMD using batch variable in query
Does anyone have an idea ?
Thanks a lot!
Expanding on my comment a little:
#Echo off
Set "server=192.X.X.X"
Set "user=myname"
Set "password=pa55w0rd"
sqlcmd -S %server% -U %user% -P %password% -Q first query
sqlcmd -S %server% -U %user% -P %password% -Q second query
You may wish to enclose your variables with relevant quoting as necessary.
From Microsoft: "Cmd.exe provides the batch parameter expansion variables %0 through %9. When you use batch parameters in a batch file, %0 is replaced by the batch file name, and %1 through %9 are replaced by the corresponding arguments that you type at the command line."
So if the number of queries you wish to execute is known just pass them in through parameters like this:
Test.bat:
#echo off
SET server=192.X.X.X
sqlcmd -S server -U user -P password -Q %1%
sqlcmd -S server -U user -P password -Q %2%
Then call Test.bat like this:
Test.bat "Select * from Test1" "Select * From Test2"
You can pass up to 9 queries this way.

Run mysql commands in bash script without logging in or adding -u root to every command

I'm writing a bash script to do some db stuff. New to MySQL. I'm on Mac and have MySQL installed via homebrew.
Am using username "root" right now and there isn't a pw set. I included the pw syntax below just to help others out that may have a pw.
My goal is to have mysql commands be as "clean" as possible in my bash script
Not a hige deal, but would like to do this if possible.
Example
# If I can do it without logging in (*ideal)
mysql CREATE DATABASE dbname;
# Or by logging in with - mysql -u root -pPassword
CREATE DATABASE dbname;
# Instead of
mysql -u root -pPassword -e"CREATE DATABASE dbname";
Tried to simplify it. I have a handful of things I gotta do, so would rather keep my code cleaner if possible. I tried logging in with the bash script, but the script stopped once logged into MySQL and didn't run any commands.
Another option I was considering (but don't really like) would be just to keep username and pw string in a var and call it for every commmand like so
# Set the login string variable
login_details="-u root -p password -e"
# example command
mysql $login_details"CREATE DATABASE dbname";
So any ideas?
Write a new bash script file and run this file after putting all your commands into it. Don't forget to give right username and password in your bash script.
For bash script:
#!/bin/bash
mysql -u root -pSeCrEt << EOF
use mysql;
show tables;
EOF
If you want to run single mysql command.
mysql -u [user] -p[pass] -e "[mysql commands]"
Example:
mysql -h 192.168.1.10 -u root -pSeCrEt -e "show databases"
To execute multiple mysql commands:
mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"
Note: -B is for batch, print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in nontabular output format and escaping of special characters. -s is silent mode. Produce less output. -e is to execute the statement and quit

Run sql script using batch file from command prompt

D:
cd Tools/MySQL5/bin
mysql -u root mysql
use xyz;
source C:/Users/abc/Desktop/xyz.sql;
\q
When I run the above lines in command prompt it works fine but when I save it as a batch file and run the file it connects to mysql but doesn't perform the sql scripts.
Now what I see is wrong here is that while executing the above commands one by one in your prompt, once you run mysql -u root mysql, you are in the mysql console. So your source command would work there but would not work in your batch since you are not in mysql console while running the batch file.
Solution:
What you can do for this is, instead of using source in mysql you can use
mysql dbname < filename
in your batch file in place of
mysql -u root mysql
use xyz;
source C:/Users/abc/Desktop/xyz.sql;
This link can assist you further if needed
This should work
mysql -u root xyz < C:/Users/abc/Desktop/xyz.sql;
It sources the SQL commands from your file
You could write something like this
mysql -u dbUsername yourDatabase -e "SELECT * FROM table;"
Or to run repeating tasks create a runtasks.bat file, save under the root of your project then write your cmd tasks inside
mysql -u dbUser -e "DROP DATABASE IF EXISTS testDatabase;"
mysql -u dbUser -e "CREATE DATABASE testDatabase;"
php index.php migration latest #runs your migration files
cd application\tests
phpunit
This would work.
mysql.exe -u user_name -p -h _host_ _schema_ -e "select 1 from dual;"
This will also give you output on same command terminal

Creating a MySQL Database Using a Variable in a BASH Script

I'm trying to create a MySQL database using a variable in a BASH script. Here is the code giving me trouble: database="mysql --verbose --user=root --password --execute="create database foo"" When run it fails with an option listing. I'm sure the issue is with the use of quotes after the execute option but I can't figure out how to get it to work.
What is the point of setting the database variable?
mysql --verbose --user=root --password --execute="create database foo"
Should work just fine for creating the database foo
Try this:
#!/bin/sh
mysql --verbose --user=root --password --execute="create database $1"
save it in your bashscript folder and run it like:
nameofbashscript mydatabasename