Home » Computing » Linux » The Power of #!/bin/bash

The Power of #!/bin/bash

 

Escaping the subshell

The pictured snippet is probably one of the dirtier pieces of code I have had the misfortune of needing – and not being able to refactor to anything cleaner.

I am trying to make bash my main programming language, and to this goal I have created a number of tools to aid me on my way: a library of code snippets that anybody can re-use, a packing tool to create executables, a pre-compilation tool to add compiler directives to bash, a build tool to pull all these together, and a make/release tool to manage versions. And I’m not yet done.

Of the main efforts here is the library of scriptlets.

Once of the main attractions of one language over the other is the availability of a large amount of re-usable code released as libraries and which are, pretty much, taken for granted.

Python can get modules from pip, there are Java libraries in JAR files around the web and even JavaScript has such libraries as jQuery to help to write terser, more manageable code more easily.

bash has none of this. And quite a few quirks. You have to contend with the very string-y way of passing data around (arrays are a bit of a nightmare until you get used to the arcane notations), and nearly every non-trivial operation you want to do is a command, an external process.

The inset image depicts some code I wrote so that assigning variables

But that is also exactly what makes so appealing – any language, and its associated libraries, can become your library!

For starters, python, perl and PHP can all be leveraged for their respective strengths in specific situations, and it is possible to write and store additional scripts such as long MySQL tasks in their own files. Use a perl script to write change on the fly, and pipe to MySQL.

Consider the following silly example:

controlapp -getusers |
    perl alter_sql.pl "$SCENARIO/mysqltemplate.sql" |
    mysql -u "$sqluser" -p"$sqlpass" "$mydb" |
    php to_xml.php |
    controlapp -dostuff

It looks quite awful at first glance, but consider the power of perl to perform text processing, keeping your mysql files ordered in a directory-based hierarchy, and passing the result to PHP which will handle outputting XML much more ergonomically than PHP.

So whilst bash does have its odd and at times even infuriating quirks, I am learning to love it.

It is now after all the de facto language of DevOps. It seems even Windows can no longer do without it :-)

Posted in Linux, Programming, Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *