Skip to main content
edited tags
Link
terdon
  • 252.2k
  • 69
  • 480
  • 718
Source Link
IGGt
  • 2.6k
  • 9
  • 36
  • 48

How to check for the first element in an Array

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.