Array not printing values if used in a loop

Hello!

I'm making an English to Morse Code translator and I was able to mostly get it all working by looking through older posts here; however, I have one small problem.

When I run it it's just printing spaces for where the characters should be. It runs the right amount of times, and if I try to individually print out of the array it works, but when I try to have it cycle through to translate I get the problem.

What I am running/output:

[acolem26@ats-cis project8]$ ./morse "a b c"
 SP  SP  EOT

My code:

#!/bash/bin

declare -A code
code[A]=".-"
code="-..."
code[C]="-.-."
code[D]="-.."
code[E]="."
code[F]="..-."
code[G]="--."
code[H]="...."
code=".."
code[J]=".---"
code[K]="-.-"
code[L]=".-.."
code[M]="--"
code[N]="-."
code[O]="---"
code[P]=".--."
code[Q]="--.-"
code[R]=".-."
code="..."
code[T]="-"
code="..-"
code[V]="...-"
code[W]=".--"
code[X]="-..-"
code[Y]="-.--"
code[Z]="--.."
code[1]=".----"
code[2]="..---"
code[3]="...--"
code[4]="....-"
code[5]="....."
code[6]="-...."
code[7]="--..."
code[8]="---.."
code[9]="----."
code[0]="-----"
code[ ]="SP"

str=$1

for (( i=0; $i < ${#str}; i++ ));
do
     printf "%s " "${code[${str:$i:1}]}"
done
printf "%s\n" EOT

If I do something like

printf "%s " "${code[A]}"

It prints off the corresponding Morse code so I assume the issue isn't with the array but with how I am substituting and I'm not sure how to fix it.

couple of things:

  1. #!/bash/bin should be #!/bin/bash
  2. . /morse "a b c" should be ./morse "A B C" as you have your array indexed by the upper-cased letters. You may upper-case your input string prior to processing tho: typeset -u str=$1 .
1 Like

In addition the bash version should minimally be 4.0 for associative arrays.

2 Likes

On the first part, actually I have that correct in my script haha just when I copy pasted it over I forgot it and typed it back in just incorrectly... ooops!

And secondly, thank you! Wow I feel really dumb for that... Guess you just always miss the smallest things...