Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I want to be able to store multiple integer arrays into a txt file when I'm done updating them, and then be able to load these arrays from the txt file into the script that I am using.

The arrays basically will contain certain statistics and I want to be able to load and save them so that they update the statistics after each execution of the script.

Is there any way to do this in bash?

EDIT: to the answer below, how would you write the arrays to the file?

share|improve this question

closed as unclear what you're asking by jasonwryan, mdpc, Archemar, cuonglm, jimmij Aug 7 at 11:29

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers 2

Suppose that we have a file with two integer arrays, one per line:

$ cat file
1 20 300
1 2 3 5

We can read those arrays in as follows:

{ read -a a1; read -a a2; } <file

We can verify that they were read correctly using declare -p:

$ declare -p a1
declare -a a1='([0]="1" [1]="20" [2]="300")'
$ declare -p a2
declare -a a2='([0]="1" [1]="2" [2]="3" [3]="5")'

Saving arrays to file

One way to save them to file is:

$ { echo "${a1[*]}"; echo "${a2[*]}"; } >newfile

The resulting file looks like:

$ cat newfile
1 20 300
1 2 3 5
share|improve this answer
    
@layshal Answer updated with a method for writing to file. –  John1024 Aug 7 at 8:06

You can write the arrays to the file with

printf "%s\n" "${a1[*]}" "${a2[*]}" > file

This is compatible with John1024's answer; it puts one array per line.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.