execute mysqlshell from within a bash script? is it possible?

All we need is an easy explanation of the problem, so here it is.

I am writing a backup script for a database and want to use mysqlshell util.dumpSchemas() utility.

But how on earth can I make it work from within a shell script?

The basic process I have is this:

filename_1: backup.sh
. . .
mysqlsh --file mysqlshell_backup.js


filename_2: mysqlshell_backup.js
\connect backup_user:<password>@127.0.0.1:3306
util.dumpSchemas(<options........>)
\q

But when I run it all I get are errors:

SyntaxError: Invalid or unexpected token at mysqlshell_backup.js:2:0
in \connect backup_user:<password>@127.0.0.1:3306

but if I run the code manually, e.g:

mysqlsh
MySQL  JS > \connect backup_user:<password>@127.0.0.1:3306

it works fine.

MySQL  127.0.0.1:3306 ssl  JS > 

I tried making the file an executable in it’s own right and running it on it’s own by adding:

#!/usr/local/mysql-shell/bin/mysqlsh --file
\connect backup_user:<password>@127.0.0.1:3306
util.dumpSchemas(<options........>)
\q

but then I get:

mysqlshell_backup.js: line 2: connect: command not found
mysqlshell_backup.js: line 3: syntax error near unexpected token `[<options>],'
mysqlshell_backup.js: line 3: `util.dumpSchemas(<options>)

But again, if I run it directly from within mysqlshell the code works fine, so I know there are no syntax errors.

Is there actually a way to run a mysqlshell command as part of a bigger script, or am I just wasting my time here?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

OK I figured this out. In the main script I can run:

mysqlsh backup_user:<password>@127.0.0.1:3306 --file mysqlshell_backup.js

meaning I can remove that line (and the \q) from the JS script.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply