command line fun – arrays

Work with new people and learn new things. I used to work with someone who was unfamiliar with the Unix world, did not know how to program in Java and couldn’t write shell scripts either.

Victoria was actually a very clever lady and she did manage to conquer these shortcomings to be the best person in our team.  She simply rolled up her sleeves (well put on some reading glasses) and got all of the knowledge that she needed to achieve her goals.

I was actually quite surprised when I was looking through one of her scripts when I saw that she was using array’s in her shell script.  I had always gathered up my files to process into a variable and then continued from there.

My file names actually had no spaces and there would only be a handful each time so my solution was just fine, but it never hurts to put another arrow into your developmental quiver.

The syntax is slightly different to other languages but the syntax is rather straightforward.

VARIABLENAME[indexhere]=somevaluegoeshere

The only thing that is different than some of the more classical languages is how to determine the length of an array.

${VARIABLENAME[@]}

I am not sure that how Victoria actually used arrays was really necessary but it did point out an interesting way we can process data in the future.

#!/bin/bash

FILELIST[0]=dailyclosing.txt
FILELIST[1]=weeklyclosing.txt
FILELIST[2]=monthlyclosing.txt

idx=0
for single in `ls -1 *`
do

  idx=$((idx + 1))

  LEN=${#FILELIST[@]}

  ndx=0
  found=0
  while [ $ndx -le $LEN ]
  do
    arrayitem=${FILELIST[$ndx]}

    #echo $single $arrayitem
    if [ "$single" == "$arrayitem" ]
    then
      found=1
    fi

    ndx=`expr $ndx + 1`
  done

  if [ $found -eq 1 ]
  then
    echo $single true
  fi

done

This solution was altered from something else that was not quite appropriate. The actual solution could have been much much simpler.

1
#!/bin/bash

if [ -f dailyclosing.txt ]
then
  echo do daily stuff
fi

if [ -f weeklyclosing.txt ]
then
  echo do weekly stuff
fi

if [ -f yearlyclosing.txt ]
then
  echo do yearly stuff
fi
This entry was posted in programming. Bookmark the permalink.