0

I am trying to find the index of an list entry using this simple method:

#!/bin/sh

partList="500 1000 2000 4000"
a=( $partList )
echo ${a["500"]}

this returns Syntax error: "(" unexpected. And the same error if I try echo ${a[500]}. Where I was hoping it would return 0 if using 500.

I am simply looking for a quick and dirty way to tell, when am looping over a list as so:

 for j in $partList; do
   if [ $j is the first entry in the list $partList ]; then
     stuff happens..
   done
 done

whether or not I have used the first element of that list and if so then do some logic.

I thought I could do this easily using the index of the list. But this appears difficult with #!/bin/sh.

Any suggestions?

Astrid
  • 167
  • 2
  • 7

1 Answers1

1

You reversed the lookup process -- array[index] returns something. array[array_element] won't give you the index - you'd need a lookup table (even better, a hash map) for that.

But for what you're doing, you are actually just looping over indices! Instead of j in $partList just loop over j in $(seq ${#partlist[@]}) and use the index to get the element.

Lastly... not even that is needed, if you are really just using the first element, why not just

j=${partList[0]}
stuff happens..
orion
  • 12,502