Jerry
2017-10-14 21:13:52 UTC
I am new to programing in bash. I am trying to copy data from an array to a
file. I got this script snippet while Googling.
for j in "${#array[@]}"
do
index=0
element_count="${j}"
while [ "${index}" -lt "${element_count}" ]
do # List all the elements in the array.
echo "${array[${index}]}" >> ${FILE}
((index++))
done
done
Now, I want to make this into a function, so I wrote it as this:
array2file () {
for j in "$1"
do
index=0
element_count="${j}"
while [ "${index}" -lt "${element_count}" ]
do # List all the elements in the array.
echo "${$3[${index}]}" >> $2
((index++))
done
done
}
The problem comes when I try to elements to it.
array2file "${#MyArray[@]}" "data_file.txt" "MyArray"
The problem is in the substitution. "j" = $1 and $2 = "data_file.txt". The
problem is I don't know how to get $3 = "MyArray" in this example. I keep
receiving an error message about a bad substitution. Is there a way to do this?
Thanks!
--
Jerry
file. I got this script snippet while Googling.
for j in "${#array[@]}"
do
index=0
element_count="${j}"
while [ "${index}" -lt "${element_count}" ]
do # List all the elements in the array.
echo "${array[${index}]}" >> ${FILE}
((index++))
done
done
Now, I want to make this into a function, so I wrote it as this:
array2file () {
for j in "$1"
do
index=0
element_count="${j}"
while [ "${index}" -lt "${element_count}" ]
do # List all the elements in the array.
echo "${$3[${index}]}" >> $2
((index++))
done
done
}
The problem comes when I try to elements to it.
array2file "${#MyArray[@]}" "data_file.txt" "MyArray"
The problem is in the substitution. "j" = $1 and $2 = "data_file.txt". The
problem is I don't know how to get $3 = "MyArray" in this example. I keep
receiving an error message about a bad substitution. Is there a way to do this?
Thanks!
--
Jerry