Self-note: Keep It Simple, Stupid

When dealing with bash (or other shells) scripts, instead of starting check outputs, write to temp file, trying to pass variables out of their scope from oine subshell to another, just remember that there is that thing called return status that can do the trick in a simpler, quicker and easier to read way.

For example, if you need to wait for a MySQL server to do not have pending queries before starting to do something, just do


while ( mysqladmin|grep -vi "show processlist"|grep "Query" > /dev/null )
do
sleep 0.1 # or whatever you want, prevent system overload
# ok, it's executing something, let's do thing A
done
# ok, it's done, let's do thing B

It’s (almost) one line long, it’s simple, effective and it just works.

Advertisements

2 thoughts on “Self-note: Keep It Simple, Stupid

  1. Nice and elegant. Small further refinement:

    while (mysqladmin | grep -vi "show processlist" | grep -q "Query" )
    do
    : that thing
    # presumably put a sleep in here as to not overload the system
    done
    # continue your script

    • Yep Phil, you’re right. :) In fact in my real life script I’ve put a sleep 0.2 to prevent overload. I’ll modify the example anyway, thanks for pointing it out

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s