Nov 10, 2018

How to execute shell commands from within the MySQL command line client

Executing shell commands from within the MySQL command line client

Now that you're started up the MySQL command line client you can execute SQL commands etc. If you want to execute a shell command, use the \! command followed by the shell command. For example, if you wanted to get a directory listing of the current working directory, you would do this:
\! ls -l
The output would then look something like this (obviously the directory listing will be different for you, and will vary depending on what the current working directory is):
mysql> \! ls -l
total 40
drwxr-xr-x 2 i88ca users 4096 Apr  18  2014 bin
drwxr-xr-x 2 i88ca users 4096 Apr  18  2014 config
mysql>
You should be able to run just about any command. You could, for example, start up a text editor such as nano or vi like this:
mysql> \! nano
or
mysql> \! vi

Dropping to a system shell

You can exit from the mysql command line client at any time using the \q command, but if you just wanted to do something quickly from the command line you can open up another system shell and then return to the MySQL client by exiting from the shell. This can save time rather than exiting MySQL because you don't need to log in again when you start the MySQL client up again.
For example, to drop to a bash shell, you would do this:
mysql> \! bash
This would then open up a bash shell. When you have finished with the system shell you would execute the normal command to exit it (e.g. "exit" or ctrl+D) and will then be returned to the MySQL command line client.

Summary

The MySQL command line client allows you to execute system shell commands which can be useful because it means you don't need to drop out from the client, run your command, and then start the MySQL client up again. You should be able to run just about any system command and can even drop out to a full system shell before returning back to the MySQL command line client again. I will look at some of the other MySQL text commands in later posts.