Monday, October 15, 2007

Array Variables in bash

In my efforts to improve my NTFS-3G mount/re-mount script, I had to learn how to implement an array variable. Turns out it's painfully simple, and now I feel that I should go back and eradicate the evil temporary files that I used in some of my earlier quickly-generated scripts. But, I digress... Here are some quick basics that proved useful:
  • Array variables can be implicitly declared, e.g. PETS=(dog cat bird fish) builds a four-element array.
  • To show the whole array, use ${PETS[*]}
  • To show the number of elements in the array, use ${#PETS[*]}
  • Element index starts at zero so ${PETS[1]} will return cat
Here's the sample code that I threw together to make sure I figured it out properly, with comments added in a different font to explain each line of the script:
#!/bin/bash
# build an array of partitions (OS X), populated only with disk#s# for each partition
TEST=(`diskutil list | egrep disk.s. | awk '{print $NF}'`)
PARTS=0
# Build a menu that shows each partition in the array
# but start numbering at 1 instead of 0
while [ $PARTS -lt ${#TEST[*]} ]; do
let COUNT=PARTS+1
echo "$COUNT".\) ${TEST[$PARTS]}
let PARTS+=1
done
# Prompt for / grab user input, and see if it matches something on the menu
echo -n Please select a partition from the menu above:
read TRYIT
case $TRYIT in
[1-${#TEST[*]}])
# NOTE: [1-3]is an expression that matches 1, 2, or 3...
echo You typed a valid number: $TRYIT;;
*)
echo You typed a bad number: $TRYIT;
exit 100; # set a non-zero exit code
esac