I am trying make a script that combines arrays on demand. Here is the script:

#! /bin/bash
declare -A code
code=( [H]="h" [E]="e" [L]="l" [P]="p" [M]="m" [E]="e" )

I need to print "help me" - without quotes and in one line - when I enter ./filename.bash "HELP ME" at command prompt. here is what I am using.

for (( i = 0; i < ${#code[@]} ; i  = $i + 1 ));
echo ${code[@]:$i:1};
  • 1
    Why are you overwriting your array with the positional parameter $1? you should be iterating over $1, using each of its characters to index into your code array, surely? – steeldriver May 11 '15 at 0:52
  • The idea here is to use $1 as a positional parameter. I have printed the code in simplest form. So, ./filename.bash "HELP ME" is $1 and code should print help me. In the same way, if I print ./filename.bash "PEEL" it should print peel in one line. Using [@] prints h e l p m e in different lines, even if I enter ./filename.bash "PEEL." – Jack Spencer May 11 '15 at 1:41
  • Why are you using arrays? it seems that the main thing you want to do is to invert the case of some text. You can do that very simply with tr "a-zA-Z" "A-Za-z" <<<"HELP ME" – and, regarding associative arrays, you can use a space for the index [' ']=' ' (if it helps). – Peter.O May 11 '15 at 4:39
  • Do you implement tr?: tr "EHLMP" "ehlmp" <<< "HELP ME" – Cyrus May 11 '15 at 5:00

Try this with script.sh "HELP ME":


declare -A code
code=( [H]="h" [E]="e" [L]="l" [P]="p" [M]="m" [E]="e" )

for ((i=0; i<${#input}; i++))
  if [[ "${input:$i:1}" = " " ]]; then     # whitespace?
    echo -n " "
    echo -n "${code[${input:$i:1}]}"


help me
  • Thank you! You are a life saver. The only other problem that I am now having is that when I add "please." after echo -n "${code[${input:$i:1}]}" it prints out hpleaseepleaselpleasepplease and so on. Also echo -n prints behind the command prompt rather than after the command prompt. – Jack Spencer May 11 '15 at 6:19
  • If you want help me please. add as last additional line: echo " please." – Cyrus May 11 '15 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.