Monday, January 12, 2009

A little tee please

Welcome to this weeks exciting new episode of Practical Shell Scripting. I'm under the gun to get a project done at work so weeks is a quickie. If you ever wanted to pipe output to both a file and the screen. Here's a fast one liner that will do it for you.

#!/bin/bash

LOGFILE="test.log"


echo "foo" | tee -a $LOGFILE



The trick is the -a for append which tee uses to print to stdio as well as where ever you direct it.

Tuesday, January 6, 2009

Inline functions in bash

Hello and welcome to this weeks edition of Practical Shell Scripting. This week I want to give a couple of examples of one the coolest things that you can do with shell scripts. I don't know if there is an actual name for this functionality, but I have always referred to them as inline functions because they remind me of the inline functions from C++. The basic deal is that you can set up one liners within a shell script to derive a certain value just as if you were calling those functions from from a shell. Here's a small shell script with a couple of examples to demonstrate what I'm talking about.

#!/bin/bash

##--------CheckForOrangeCount ----------##
CheckForOrangeCount()
{

if [ -f $FILE_NAME ]; then
FILE_NAME="$1"
SomeValue=`grep oranges $FILE_NAME | cut -d" " -f2`
echo "There are $SomeValue oranges"
else
echo "No file to check out"
fi

}

##-------- main----------##

UPTIME=$(cat /proc/uptime | cut -f1 -d' ' | cut -f1 -d'.')
echo "Your system has been up for $UPTIME"



if [ "$1" = "" ]; then
echo "You got no incoming files to work on"
else
echo "You've got $1"
FILE_NAME="$1"
CheckForOrangeCount $FILE_NAME
fi

##--------------------------------------------------------------------------##


There are two instances of these in this piece of code. The first one to show up is one that
tells us how long the system has been running since the last boot up.

UPTIME=$(cat /proc/uptime | cut -f1 -d' ' | cut -f1 -d'.')

The next is one that tells us the number number of oranges in a text file, presumably a grocery list of some sort.

SomeValue=`grep oranges $FILE_NAME | cut -d" " -f2`

Notice that there are two different formats here. The first one uses $( ) to retrieve the value for how long the system has been up. While the second one uses a format similar to an alias. In fact except for the keyword alias these are essentially identical from a functional point of view.

These are two very simple examples, but you can make these as complicated or as simple as you like. Just remember that there's always the probability that you will need to decipher them at some time in the future.

That's it for this week, as always if you have any questions or comments please feel free to contact me and Happy coding.