4

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...

  • ***[HERE](http://stackoverflow.com/questions/7823079/write-some-lines-to-a-file-with-a-bash-script)*** is some discussion on similar questions. – ryyker Sep 17 '13 at 21:50
  • @ryyker No that's different. – konsolebox Sep 17 '13 at 21:56
  • @konsolebox - Yes, the 5 minute timer clicked faster than 5 minutes. I also meant to post ***[THIS](http://stackoverflow.com/questions/4685323/bash-read-array-from-external-file)***. it addresses the question on reading data from a file. Thank you – ryyker Sep 17 '13 at 21:59
  • @ryyker That won't solve the problem with multi-lined arrays. – konsolebox Sep 17 '13 at 22:01
  • @konsolebox - It most certainly does handle multi-lined files (or arrays). Did you look? [look here](http://stackoverflow.com/a/7220619/645128) and [here](http://stackoverflow.com/a/4687512/645128) both links from the same post. – ryyker Sep 17 '13 at 23:32
  • @ryyker I'm sorry but it seems that you never understood the concept. Those would break if one of the elements contains at least something like "AB". Imagine how that could be saved to and reloaded from files without breaking values with those methods. – konsolebox Sep 17 '13 at 23:43
  • @konsolebox - Your understanding exceeds mine, +1 for your answer. – ryyker Sep 18 '13 at 15:55

2 Answers2

4

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.

konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

Does this work for you ?

a.sh loads the array to a variable ARR.

content of a.sh:

#/bin/sh
ARR=("aaa" "bbb" "ccc")
echo ${ARR[@]};

b.sh sources a.sh and obtain the same variable ARR

content of b.sh :

#/bin/sh
source a.sh
echo "I am in b.sh"
echo ${ARR[@]};

execute b.sh

./b.sh
I am in b.sh
aaa bbb ccc
iamauser
  • 11,119
  • 5
  • 34
  • 52