-1

Let's make this example:

echo "Choose your color and number: "

My answer: Blue 2

I want to read the first word and the second word, something like this:

read COLOR NUMBER

and then I can use $COLOR (first word, or Blue) and $NUMBER (second word, or 2) as variables

How can I do it? Thanks

jww
  • 97,681
  • 90
  • 411
  • 885
  • 3
    Uhm.. That's exactly how you do it. – that other guy Jan 02 '19 at 22:30
  • Did you actually *try* your pseudocode before asking? :) – Charles Duffy Jan 02 '19 at 22:36
  • 2
    BTW, better to use lowercase names for your own variables -- that way you don't stomp on reserved names meaningful to the shell. See the relevant standards documentation at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html: *The name space of environment variable names containing lowercase letters is reserved for applications. Applications can define any environment variables with names from this name space without modifying the behavior of the standard utilities* -- true for regular shell variables too, because setting one overwrites any like-named environment variable. – Charles Duffy Jan 02 '19 at 22:36
  • 1
    Possible duplicate of [How to use the read command in Bash?](https://stackoverflow.com/q/7676045/608639) – jww Jan 04 '19 at 05:16

1 Answers1

1
  • Use read word1 word2 ... wordN to assign words to $wordN:

    echo "word1: $word1"
    echo "word2: $word2"  
    echo "wordN: $wordN"
    
  • Use -a array to access the words using their index.

    echo "${array[0]}"
    echo "${array[1]}"
    

See man page:

read [-a array][name ...]

The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with any leftover words assigned to the last NAME.

-a array assign the words read to sequential indices of the array variable ARRAY, starting at zero

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Laurens Deprost
  • 1,653
  • 5
  • 16