1

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.

code=1ドル;
for (( i = 0; i < ${#code[@]} ; i = $i + 1 ));
do;
echo ${code[@]:$i:1};
done
jimmij
48.6k20 gold badges135 silver badges140 bronze badges
asked May 10, 2015 at 23:20
4
  • 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? Commented May 11, 2015 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." Commented May 11, 2015 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). Commented May 11, 2015 at 4:39
  • Do you implement tr?: tr "EHLMP" "ehlmp" <<< "HELP ME" Commented May 11, 2015 at 5:00

1 Answer 1

1

Try this with script.sh "HELP ME":

#!/bin/bash
input=1ドル;
declare -A code
code=( [H]="h" [E]="e" [L]="l" [P]="p" [M]="m" [E]="e" )
for ((i=0; i<${#input}; i++))
do
 if [[ "${input:$i:1}" = " " ]]; then # whitespace?
 echo -n " "
 else
 echo -n "${code[${input:$i:1}]}"
 fi
done

Output:

help me
answered May 11, 2015 at 4:52
2
  • 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. Commented May 11, 2015 at 6:19
  • If you want help me please. add as last additional line: echo " please." Commented May 11, 2015 at 17:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.