I'd like to create a variable from an array element from two arrays. In my search for answers I found this code for bash that joins two arrays and then started to work with it. I had got to work once and then foolishly without saving the code, I started to edit it for ksh and subsequently broke it. Now I can't get it to work again. Any suggestions?
# this gets args from command line and add them to the arrays.
# it's NOT the Right Thing, but can give you a brief idea of what to do
# You may add options, like -name "list" -surname "list" to parse the
# correct elements and insert them in the appropriated array.
for i in $@
do
# this ugly stuff inside brackets counts the number of elements
# so every new element added increases array counter.
NAME[${#NAME[@]}]=$i
SURNAME[${#SURNAME[@]}]=$i
done
# starts loop at element 0 and stops at last.
for ((i=0; i < ${#NAME[@]}; i++))
do
# echo element number, name and surname.
echo "Howdy #$i: ${NAME[$i]} ${SURNAME[$i]}"
done
Basically what I want to do is take SURNAME and assign it to NAME as a variable for each element.
This is what I have come up with... ( adding/changing - [ typeset NAME[$i]="${SURNAME[$i]}" ])
#!/bin/bash
NAME="John" "Mary" "Fred"
SURNAME="Doe" "Poppins" "Flintstone"
for i in $@
do
NAME[${#NAME[@]}]=$i
SURNAME[${#SURNAME[@]}]=$i
done
for ((i=0; i < ${#NAME[@]}; i++))
do
typeset NAME[$i]="${SURNAME[$i]}"
done
echo "$John"
echo "$Mary"
echo "$Fred"
As I mentioned in my original post I got it to work another way and couldn't replicate it again. I was just wondering if it was a fluke or another way of assigning an array I was not aware of.
A follow-up question to this is how I would approach combining the two arrays together into another single array?
example: display_name="NAME[$i] ${SURNAME[$i]}"
So that it would echo ${display_name[0]} and return "John Doe"