Automating stuff with shell scripts (Including MySQL commands)


Yesterday I was debugging a C project that stores a lot of data in the filesystem and in a MySQL database. And I found myself repeating the same commands everything I fixed something and restarted the application. Those commands where:

$ rm -rf debug_*
$ rm -rf data && mkdir data
$ mysql -u root -proot
mysql> USE db_name;
mysql> DELETE FROM table_name WHERE id > 0;
mysql> quit

And believe me, after a while you get really fast at this… but it’s still unnecessary!!

So I decided to create a shell script called to automate this process. And, while the first commands are really straightforward, running MySQL commands, in a shell script, it’s a little bit more complex if you are not used to do it through the command line!

So, if you ever need to do something like this, here is my script:

# Clean data script
rm -rf data \
&& mkdir data \
&& mysql -u root -proot -Bse "USE db_name;DELETE FROM table_name WHERE id > 0;" \
&& rm -rf debug_* \
&& echo "Cleaned!"

After saving your file with this content on it, you just need to give execution permissions and run it!

$ chmod 755
$ ./

And you are good to go…
PS: Your keyboard will thank you for that!