what i mean is does x know that it’s working on position [1] or [2] or [3] in the list?
if so what would be the nomenclature? ${x[@]}
so that i just say if ‘x’ is at this position then do this?
alist=(3 5 7)
blist=(Pling Plang Plong)
for x in ${alist[@]}; do
…if command; then echo "${blist["${x[@]}"}"
…fi
done.
i ran this against shellcheck on my cli and nothing came up for an error
thanks
This is exactly the sort of question which mentor discussions are built for. I’d encourage you to request mentoring, if you’re not, to pose these questions to the bash mentors (like myself).
Note: you can use a codeblock for your code here:
```bash
for i in …; do
echo “$i”
done
```
=>
for i in ...; do
echo "$i"
done
To answer your question … the short answer is “no”. bash may track the index internally but that’s not exposed to the script. bash manages the loop variable (x) for you and assigns it a value. There’s no simple way to know where in the list you are.
You could iterate though the list index values, though.
for (( index = 0; index < "${#alist[@]}"; index++ )); do
echo "Index: ${index}"
factor="${alist[index]}"
sound="${blist[index]}"
printf 'Index=%d, factor=%d, sound=%s\n' "${index}" "${factor}" "${sound}"
done
That said … I’d encourage you to seek mentoring. Maintaining two distinct lists and having to map one to the other by a shared index is not ideal.
hi isaac
i’ve been going through this “raindrops” problem and seeing if i could do it different ways and my first thought originally was a for loop and started to write it out, yet with a list, i couldn’t figure out a way to only echo the one word for a true answer. it was running all three in the list and echoing all three, since they were all true at one time through the list, i was hoping to not have to type all of it out.
i thought that i could do it with if, elif statements yet couldn’t get it to get past the first true ,"0" answer.
rewrote it with only if statements, which is out putting properly except for the $1 if it’s false for the rest. so that’s what i’m doing now.
testing things out with an echo $? after each to see what the output is, “0” or “1” and figuring out how to write the last statement.
i’ve read your reply a number of times now and it’s making sense so i will try it both ways, with a for and all if s and submit both or maybe all three ways of thinking about it.
Please do get one working then use the “Request Code Review”. A mentor on the site would be able to see your code and help you work out an optional solution (IMO that means using a sparse array).