I have the following Array Loop set up. It simply loops through a string and checks to see if each item matches a letter and sets some variables accordingly.
#!/usr/bin/env bash
IN="ItemName -a -b"
itemA=0
itemB=0
itemI=0
while IFS=' -' read -ra ARR; do
for x in "${ARR[@]}"; do
echo "x = $x"
y=${x:0:1}
echo "y = $y"
case $y in
"a") itemA=1 ;;
"b") itemB=1 ;;
"I") itemI=1 ;;
esac
done
done <<< "$IN"
echo "itemA is $itemA
echo "itemB is $itemB"
echo "itemI is $itemI"
However, for the first element ("itemName"), I need to set this separately, so that it isn't checked as part of the case stemement. Ideally I want to end up with:
itemName is ItemName
itemA is 1
itemB is 1
itemI is 0
How can I check for the first element? I tried
if [ ${ARR[0]} ] ; then
itemName=$x
else
. . .
fi
but ended up with none of the variables getting set.
ItemName -a -b -I
orAnotherItem -a -b
thenItemI
will be wrong. Is there simply a way of sayingif this is the first item in an Array do this else do that
? – IGGt Dec 10 '15 at 14:26getopts
looks overly complex for my needs, Plus I couldn't get it to work, but cheers anyway – IGGt Dec 10 '15 at 14:36