Using mysql in Shell Scripts
Problem
You want to invoke mysql from within a shell script rather than using it interactively.
Solution
There’s no rule against that. Just be sure to supply the appropriate arguments to the command.
Discussion
If you need to process query results within a program, you’ll typically use a MySQL programming interface designed specifically for the language you’re using (for example, in a Perl script you’d use the DBI interface). But for simple, short, or quick-and-dirty tasks, it may be easier just to invoke mysql directly from within a shell script, possibly postprocessing the results with other commands. For example, an easy way to write a MySQL server status tester is to use a shell script that invokes mysql, as is demonstrated later in this section. Shell scripts are also useful for prototyping programs that you intend to convert for use with a standard API later.
For Unix shell scripting, I recommend that you stick to shells in the
Bourne shell family, such as
sh, bash, or
ksh. (The csh and
tcsh shells are more suited to interactive use
than to scripting.) This section provides some examples showing how
to write Unix scripts for /bin/sh. It also
comments briefly on DOS scripting. The sidebar
“Using Executable Programs”
describes how to make scripts executable and run them.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access