Shell scripting


The great thing about Mac OS X is that it’s BSD-based, so naturally has all the flexibility of Linux right? Well most of the time… Linux is a UNIX derivative, and so is BSD, but every now and then there’s a quirk where the two disagree on how things should be done. One example of this is seq vs. jot. For generating a sequence of numbers, Linux has the “seq” command:
$ echo `seq 1 1 10`
1 2 3 4 5 6 7 8 9 10

BSD has the “jot” command:
$ echo `jot 10 1 10`
1 2 3 4 5 6 7 8 9 10

The tricky part comes in when you want to do stuff like zero padding, because the two commands take different arguments. seq’s syntax is “seq start increment end” whereas jot’s is “jot count start end”. To zero-pad seq, use its -f format flag:
$ echo `seq -f %02g 1 1 10`
01 02 03 04 05 06 07 08 09 10

With jot, use its word flag:
$ echo `jot -w %02d 10 1 10`
01 02 03 04 05 06 07 08 09 10

What bugs me about bash scripting – and don’t get me wrong, I love what it can do, and I find the manner it accomplishes things to be elegant – is that I can never remember the syntax. I spend so much time in a language like Java or C++ that remembering what a bash if statement looks like can be a challenge without pulling up an old script.
if [ "$CONNECT" != "go" ] ; then

And of course a for loop for good measure:
LIST="Alpha Beta Gamma"
for i in $LIST ; do
   echo $i

Convert string to upper case:
echo $string| tr [:lower:] [:upper:]

And let’s take the third word out of the last line of a command’s output:
echo $cmdout| tail -n 1 | cut -d " " -f 3


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: