How to save array to file and another file array load?
file1.sh
ARR=("aaa" "bbb" "ccc");
save to file2; # I do not know how :-(
and
file3.sh
load from file2; # I do not know how :-(
echo ${ARR[@]};
I tried...
file1.sh
declare -a ARR > /tmp/file2
and
file3.sh
source /tmp/file2
echo ${ARR[@]};
does not work :-( Advise someone better way? Thank you...
If the values of your variables are not in multiple lines, a basic and easy way for it is to use set:
# Save
set | grep ^ARR= > somefile.arrays
# Load
. somefile.arrays
But of course if you're somehow security sensitive there are other solutions but that's the quickest way to do it.
Update for multi-lined arrays:
# Save
printf "%s\x00" "${ARR[@]}" > somefile.arrays
# Load
ARR=() I=0
while read -r ARR[I++] -d $'\0'; do continue; done < somefile.arrays
That would work if your values doesn't have $'\0'
anywhere on them. If they do, you can use other delimeters than $'\0'
that are unique. Just change \x00
and $'\0
accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With