Skip to content
Advertisement

read -a not working as expected in Bash

For some reason when using “read -a” my script is only taking the first element of the line into the array. For example, when inputting a string such as “canada China”, the output of the program simply reads:

JavaScript

Instead of:

JavaScript

The instructions for my assignment are as follows:

Create a script that reads the user’s input and stores it in an Array. Then, loop over the Array and :

  • If the first character is lowercase, change it to be uppercase and write next to it “Changed to uppercase”.
  • If the first letter is already uppercase, output the input word then write next to it “Already uppercase”.
  • If the first character is not a letter, output the input word then write next to it “Doesn’t Start with a letter”. Use an Associative Array to do the conversion from lowercase to uppercase [converterArray=([a]=A [b]=B …)]

And here is my code:

JavaScript

EDIT: Thanks to John’s help the problem has been solved. I also fixed an issue with checking the case of the letter ([a-z] vs. [[:lower:]]), and removed the unnecessary “echos” for debugging.

JavaScript

(2nd edit: Fixed line where I forgot to put spaces around equals sign, originally forgotten in previous edit)

Advertisement

Answer

If $array is an array, "${array[@]}" gives all of the array elements. A bare $array references only the first element.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement