Using MySQL in a Shell Script

Every once in a while I come across the need to access data that is stored in a database inside MySQL from a shell script. Here is a quick and dirty way to access that information without having to resort to PHP or Perl.

Run a SELECT:

By default this would return output like:

id
514

So we need to use sed to remove the name of the field.

SITEID=$(mysql -D database -u root –password=password –silent –exec=”SELECT id FROM domains WHERE name = ‘`echo $SITE`’;” |sed ‘s/id//’)

Since INSERTs, UPDATEs and DELETEs don’t return any information you won’t need to pipe the information returned from MySQL to sed.

This handy tip will work for basic MySQL queries, but for more complex queries, I would recommend something with a little more control over the information such as PHP or Perl.

I hope that helps somebody.

Comments (0)

› No comments yet.

Pingbacks (0)

› No pingbacks yet.