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

7
  • HERE is some discussion on similar questions. Commented Sep 17, 2013 at 21:50
  • @ryyker No that's different. Commented Sep 17, 2013 at 21:56
  • @konsolebox - Yes, the 5 minute timer clicked faster than 5 minutes. I also meant to post THIS. it addresses the question on reading data from a file. Thank you Commented Sep 17, 2013 at 21:59
  • @ryyker That won't solve the problem with multi-lined arrays. Commented Sep 17, 2013 at 22:01
  • @konsolebox - It most certainly does handle multi-lined files (or arrays). Did you look? look here and here both links from the same post. Commented Sep 17, 2013 at 23:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.