Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell/Bash - How to save array to file and another file array load?

Tags:

bash

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

like image 930
Veronika Lipská Avatar asked Sep 06 '25 03:09

Veronika Lipská


1 Answers

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.

like image 184
konsolebox Avatar answered Sep 07 '25 20:09

konsolebox