How to separate different data values in a list and assign to variables in a shell script?

Let's say I have a list of data in a shell script like this:

DataList = ["
Cat
Dog
Rabbit
GuineaPig
Hamster
"]

Now, how I would I go about setting each separate data value in the list as a variable? Like this:

$Value0 = "Cat"
$Valu1 = "Dog"
$Value2 = "Rabbit"
$Value3 = "GuineaPig"
$Value4 = "Hamster"

For the record, I am familiar with commandline utilities like Grep, AWK, and SED. However, I am not quite sure where to begin with something like this.

Also, for the record, my preferred shell is Fish, however feel free to answer in BASH or SH formatting. Don't worry, I can translate.


Solution 1:

Not sure of what you Need. does this help?

#!/bin/bash
DataList=(
Cat
Dog
Rabbit
GuineaPig
Hamster
)

for i in {0..4}
do
    value[$i]=${DataList[$i]}
    echo "value[$i] = ${value[$i]}"
done

outputs:

value[0] = Cat
value[1] = Dog
value[2] = Rabbit
value[3] = GuineaPig
value[4] = Hamster

Solution 2:

Since your preferred shell is Fish, I'll offer three options.

First, given the DataList in a string format, you can use string split to split the individual lines into an actual list:

> set DataList "
  Cat
  Dog
  Rabbit
  GuineaPig
  Hamster
  "

> set --show DataList

$DataList: set in global scope, unexported, with 1 elements
$DataList[1]: |\nCat\nDog\nRabbit\nGuineaPig\nHamster\n|

> set Value (string split -n \n "$DataList")
> set --show Value

$Value: set in global scope, unexported, with 5 elements
$Value[1]: |Cat|
$Value[2]: |Dog|
$Value[3]: |Rabbit|
$Value[4]: |GuineaPig|
$Value[5]: |Hamster|

> echo $Value[2]

Dog

^ Blank lines in the example are purely for readability and do not appear in the actual output

But if you can, just embed the data as a list literal in the script anyway and avoid the extra string split:

> set DataList "Cat" \
  "Dog" \
  "Rabbit" \
  "GuineaPig" \
  "Hamster"

> set --show DataList

$DataList: set in global scope, unexported, with 5 elements
$DataList[1]: |Cat|
$DataList[2]: |Dog|
$DataList[3]: |Rabbit|
$DataList[4]: |GuineaPig|
$DataList[5]: |Hamster|

> echo $DataList[2]
Dog

Finally, your question, taken literally, is to separate the list into variables, rather than a variable containing a list. I assume that's not really what you meant. It would be a bit pathologic, IMHO, since you would lose the ability to easily count, iterate, and index the results, but it can be done ...

set DataList "
Cat
Dog
Rabbit
GuineaPig
Hamster
"

set v (string split -n \n "$DataList")

set scrpt (for i in (seq (count $v))
             echo 'set Value'(math $i-1) '"'$v[$i]'"'
           end)

eval (string join ";" $scrpt)
set --erase v
set --erase scrpt

Results in:

$Value0 = "Cat"
$Value1 = "Dog"
$Value2 = "Rabbit"
$Value3 = "GuineaPig"
$Value4 = "Hamster"