Hello and welcome to this weeks installment of Practical shell scripting. This week I'm going to tackle something which is common in most coding languages, but it's handled a little differently in bash shell scripts, that is arrays. Hopefully most of you know that an arrays is a collection of like pieces of data. The data could be integers, or strings, or floats or whatever. For those of who come from a C/C++ background there are several things which are a little on the annoying side about using arrays in shell script. Firstly bash will allow you to mix data types that's because bash and I believe Bourne and Korn as well are what's referred to as loosely typed languages. So for instance in a language like C/C++ you define an arrays being of a specific data type. For example:
int MyNumbers[5]={1,3,5,7,11};
is a single dimensional array which will hold 5 integers, but if you try and introduce other variable types you will fail to compile. Bash on the other hand will you get away with a lot more. Also in Bash it's perfectly acceptable to declare your array without any predefined size, or variable type. So for instance in bash an array might look like this:
SomeAray="1 3 5 7 eleven";
However, the nice thing about bash arrays is that they follow a similar syntax regarding the syntax of the indexes, and like arrays in C/C++ they both start at 0. The only other tricky thing to remember is that in bash arrays are referenced using ${ }. As opposed to C/C++ where the array is just referenced directly. So to represent the fifth element of the C/C++ array you would refer to it as:
MyNumbers[4];
While in Bash you would reference the fifth element as:
${SomeArray[4]}
There are also a few nifty little things about bash arrays that I'm just starting to explore myself, but here's some code to play with to give you some ideas of what you can do with bash arrays.
#!/bin/bash
##-----------------------------------------------------------------##
##
## A simple shell script to give examples of arrays
##
##-----------------------------------------------------------------##
##--- example one ----##
echo "EXAMPLE 1: array of integers"
Array=(1 3 5 7 eleven)
echo "Here's the values"
for value in ${Array[*]}
do
echo "value is $value"
done
echo ""
echo "Here's the index"
for index in ${!Array[*]}
do
echo "index is $index"
done
echo ""
echo "Here's the index and it's corresponding value"
for index in ${!Array[*]}
do
echo "index is $index, value is ${Array[$index]}"
done
##--- example two ----##
echo ""
echo "So the value at index 2 is ${Array[2]}"
echo ""
echo "EXAMPLE 2: array of strings "
NewArray=(Apples Oranges Pears Beans 99)
echo "NewArray[0] is ${NewArray[0]}"
echo "NewArray[1] is ${NewArray[1]}"
echo "NewArray[2] is ${NewArray[2]}"
echo "NewArray[3] is ${NewArray[3]}"
echo "NewArray[4] is ${NewArray[4]}"
Notice how you can mix and match strings in with integers in the array and bash doesn't even care. There's a couple of other neat tricks that you can do with arrays, but I'll save that for next weeks entry. That's it for this week, as always if you have any questions or comments please feel free to contact me and Happy coding.
Showing posts with label shell script. Show all posts
Showing posts with label shell script. Show all posts
Monday, December 29, 2008
Monday, December 8, 2008
Simple loops and counters in bash
Welcome to this weeks issue of Practical Shell Scripting. Last week I gave an example and explanation of a shell script that did some reading from a text file in a line by line fashion. This week I'm going to give a discussion of basic looping and simple math comparison. First lets look at the basics of doing simple math and comparison testing. Then I'll give a real world example of when this stuff might be used.
One of the confusing things for me is the syntax that bash uses for incrementing. The basic construct is just like that of basic, and I think maybe pascal and cobol, but it's been a while
since I coded in those languages. Specifically bash uses the word let to carry out arithmetic operations. However, here's where it gets a little funky. Instead of a simple statement like
let A=A+1
Which is how this is done in most formal languages. However bash uses an expression like this:
let $((COUNTER=$COUNTER+1))
In order to get this right and make it work the $(( on the left side must be just like that and the variable COUNTER must be next to them. While the second half must be $COUNTER, referencing the variable as one normally would. If the syntax is not exactly like this you can pretty much count on having some problems.
How and why this works is something that I have no idea. I only know that it does, perhaps someday in my travels this will be revealed to me, but for now I'm willing to take it for granted
that this is simply how we do things in bash. There is another syntax for doing math that I have come across in some bash scripts, however I have found that it doesn't always work with every version of bash and the example that I have given seems to be very portable across older and newer version.
I have one more topic that I need to bring up here before we get into the whole code example, and that is comparison operators. Bash uses a collection of acronym like operators to do comparison, you see the same syntax in perl. However, for us C/C++ guys it looks pretty strange. The basic operators are:
-eq ##equal to
-ne ## not equal to
-le ## less than or equal to
-lt ## less than
-gt ## greater than
-ge ## greater than or equal to
Now here's an example of a very simple while loop that uses both a math variable that gets incremented and a comparison operator to break the loop.
#!/bin/bash
##---------------------------------------------------------------------##
##
## This is a simple looping example with a counter and
## a math comparison operator.
##
##
##---------------------------------------------------------------------##
COUNTER=0
MAX_SIZE=10
while [ $COUNTER -lt $MAX_SIZE ]
do
let $((COUNTER=$COUNTER+1))
echo $COUNTER
sleep 1
done
Now I'd like to share a real world example that I had to write a few years back to do some house cleaning in a directory to make sure that we didn't overflow the drive. The company I work does automated nightly builds using a cron job to make sure that the coders didn't break anything during the days work. Also, there are additional day builds in the same directory to test quick fixes and branch merges. Each build takes up around 100 to 150 megabytes of space. So the problem turns up when after a while the builds end up taking up the whole drive and then at some point the next nightly build fails and some one has to go about the time consuming and tedious job of purging off the old builds. So we came up with a rule that we would keep the most current 10 builds and all the previous ones would be deleted. If anyone wanted a specific build to be saved off that was his responsibility to do so. The house-cleaning script would be run before the regular builds were run to make sure that there was enough room.
#!/bin/bash
# this is the house-cleaning.sh
# it makes sure that there are not a lot
# of silly old bulds laying around taking up
# space
#
#
#-----------------------------------------------------
#
# $Id: $
# $Change: $
# $Author: tglaser $
# $Date: 2008/11/06 $
# $NoKeyword: $
#
#
#-------------------------------------------------------
HOME=/home/tglaser
DERIVEDDIR=$HOME/BuildDir
cd $DERIVEDDIR
pwd
counter=0
too_many_files=5
for file in `ls -t`
do
echo $file
let $((counter=$counter+1))
if [ $counter -gt $too_many_files ]; then
echo "there are $counter files or directories"
echo "So we are going to delete $file";
rm -rf $file;
else
echo "you've still got room to work here"
echo "No need to delete anything yet"
fi
echo " "
echo " "
sleep 3
done
cd $HOME
exit
##----------------------------------------------------##
The only important difference between this script and the first one is the for loop which I will go into in one of the next issues. So that's it for this week. As always if you have any questions or comments please feel free to contact me. Happy coding.
One of the confusing things for me is the syntax that bash uses for incrementing. The basic construct is just like that of basic, and I think maybe pascal and cobol, but it's been a while
since I coded in those languages. Specifically bash uses the word let to carry out arithmetic operations. However, here's where it gets a little funky. Instead of a simple statement like
let A=A+1
Which is how this is done in most formal languages. However bash uses an expression like this:
let $((COUNTER=$COUNTER+1))
In order to get this right and make it work the $(( on the left side must be just like that and the variable COUNTER must be next to them. While the second half must be $COUNTER, referencing the variable as one normally would. If the syntax is not exactly like this you can pretty much count on having some problems.
How and why this works is something that I have no idea. I only know that it does, perhaps someday in my travels this will be revealed to me, but for now I'm willing to take it for granted
that this is simply how we do things in bash. There is another syntax for doing math that I have come across in some bash scripts, however I have found that it doesn't always work with every version of bash and the example that I have given seems to be very portable across older and newer version.
I have one more topic that I need to bring up here before we get into the whole code example, and that is comparison operators. Bash uses a collection of acronym like operators to do comparison, you see the same syntax in perl. However, for us C/C++ guys it looks pretty strange. The basic operators are:
-eq ##equal to
-ne ## not equal to
-le ## less than or equal to
-lt ## less than
-gt ## greater than
-ge ## greater than or equal to
Now here's an example of a very simple while loop that uses both a math variable that gets incremented and a comparison operator to break the loop.
#!/bin/bash
##---------------------------------------------------------------------##
##
## This is a simple looping example with a counter and
## a math comparison operator.
##
##
##---------------------------------------------------------------------##
COUNTER=0
MAX_SIZE=10
while [ $COUNTER -lt $MAX_SIZE ]
do
let $((COUNTER=$COUNTER+1))
echo $COUNTER
sleep 1
done
Now I'd like to share a real world example that I had to write a few years back to do some house cleaning in a directory to make sure that we didn't overflow the drive. The company I work does automated nightly builds using a cron job to make sure that the coders didn't break anything during the days work. Also, there are additional day builds in the same directory to test quick fixes and branch merges. Each build takes up around 100 to 150 megabytes of space. So the problem turns up when after a while the builds end up taking up the whole drive and then at some point the next nightly build fails and some one has to go about the time consuming and tedious job of purging off the old builds. So we came up with a rule that we would keep the most current 10 builds and all the previous ones would be deleted. If anyone wanted a specific build to be saved off that was his responsibility to do so. The house-cleaning script would be run before the regular builds were run to make sure that there was enough room.
#!/bin/bash
# this is the house-cleaning.sh
# it makes sure that there are not a lot
# of silly old bulds laying around taking up
# space
#
#
#-----------------------------------------------------
#
# $Id: $
# $Change: $
# $Author: tglaser $
# $Date: 2008/11/06 $
# $NoKeyword: $
#
#
#-------------------------------------------------------
HOME=/home/tglaser
DERIVEDDIR=$HOME/BuildDir
cd $DERIVEDDIR
pwd
counter=0
too_many_files=5
for file in `ls -t`
do
echo $file
let $((counter=$counter+1))
if [ $counter -gt $too_many_files ]; then
echo "there are $counter files or directories"
echo "So we are going to delete $file";
rm -rf $file;
else
echo "you've still got room to work here"
echo "No need to delete anything yet"
fi
echo " "
echo " "
sleep 3
done
cd $HOME
exit
##----------------------------------------------------##
The only important difference between this script and the first one is the for loop which I will go into in one of the next issues. So that's it for this week. As always if you have any questions or comments please feel free to contact me. Happy coding.
Subscribe to:
Posts (Atom)
