Thursday, August 6, 2009

MySQL bash shell one-liners

This is a useful thing to know if you're ever trying to use data in files to grab data from a MySQL database: You can feed in SQL query strings to the mysql client in the bash/shell standard way:

bash> mysql -u paul -h myhost -pmypass test_paul <<< "SELECT id from a_table where a_name='boo-yah';"

Which means that you can put this in a shell script (or Perl script, or whatever). For example, to print out the addresses associated with a set of names:


for name in `cat names.list`;
do address=`mysql -u paul -h myhost -pmypass test_paul <<< "SELECT address from a_table where a_name='$name';"`; echo "$name -> $address";
done

4 comments:

  1. right!!! and putting in mysql user/pass in a sheel script is a good idea?

    ReplyDelete
  2. C'mon, this is just an example. If you were writing a script that you wanted to save you'd write it to accept command line arguments defining the MySQL username/password.

    The for loop example was run on the command line and not saved.

    ReplyDelete
  3. Everybody on a Linux system can see everyone's command lines. So, bad idea from a security perspective.

    Still, thanks for the post! :)

    ReplyDelete
  4. Thanks! Your posting helped me! I had just to make a small few changes:

    mysql --user=USERNAME --password=PASSWORD MYDATABASE -e 'SELECT name FROM friends;'

    ReplyDelete