0

I am trying to loop though an array in bash. The array is "AARON" currently that array fills index 0 with AARON. I want to be behave as such

ara[0] = A
ara[1] = A
ara[2] = R
ara[3] = O
ara[4] = N

My script currently looks like this.

 #!/bin/bash declare count declare -a ara=(AARON) for name in {A..Z} do count=$((count++)) for char in ${ara[*]} do if [[ ${ara[char]} -eq $name ]] echo ${ara[char]} # for debugging purposes. then sum=$((sum + count)) fi done done echo $sum #for debugging purposes. 

Normally I would achieve this by setting a custom IFS but I don't know how I would do that for each character of string.

2 Answers 2

3

You want = not -eq for string comparison.

Your echo ${ara[char]} line is part of your if test not part of the if body.

Your count=$((count++)) assignment doesn't work correctly (it always sets count to zero) you want ((count++)) or count=$((++count)) instead.

You can use ${strvar:pos:count} to get parts of a string.

So something like this:

#!/bin/bash declare count declare -a ara=(AARON) for name in {A..Z} do ((count++)) for ((i=0; i<=${#ara[0]}; i++)) do echo ${ara[0]:i:1} # for debugging purposes. if [[ ${ara[0]:i:1} = $name ]] then sum=$((sum + count)) fi done done echo $sum # for debugging purposes. 
Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done; in the spirit of ((count++)): sum=$((sum + count)) could be simplified to ((sum += count)).
0

I would do something like this:

declare count declare -a ara=(A A R O N) for name in {A..Z} do for character in ${ara[*]} do if [[ ${character} == ${name} ]] then echo ${character} '=' ${name} # for debugging purposes. let 'sum=sum+1' fi done done echo $sum #for debugging purposes. 

You could add spaces into every letter to convert AARON in a bash array. Moreover, you could use "let" to inrease the counter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.