0

I am saving my global variable arrays to a file with this:

declare -p hashTable  > $File
declare -p testArray >> $File

I would like to load them back to global variables. I was using this:

source $File

That is fine when called from the global scope, but when it is within a function, it loads the variables back as local.

Is there a way to load them to globals? Is there a way to save with the -g option so it loads globally?

1
  • 2
    declare was never designed to be a (de)serialization tool. You are better off using a different language if you want this type of control. Commented Mar 6, 2018 at 15:46

2 Answers 2

2

On BASH 4.2+, you can source script as this inside your function:

fn() {
   source <(sed 's/^declare -[aA]/&g/' "$File")
}

# access your array outside the function
declare -p testArray

This sed will find lines starting with declare -a or declare -A and replace them with declare -ag thus making all the array as global.

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

7 Comments

Note this can break in extreme cases, such as if \ndeclare -a is part of the value of an array element.
Unavoidable corner cases aside, you might want to make it -[aA] to handle associative arrays as well.
1st: declare -p hashTable testArray | sed 's/ -[aA]/&g/' >$File, then no need to use sed again... I won't post this: +1 for g switch!
and declare in s/declare -[aA] is useless, as sed will consider 1st occurence of space - aA.
@F.Hauri Could you clarify what you mean by "declare... is useless". I can't follow what by "...space - aA"
|
1

My two cents:

There are 2 way of doing this:

  1. use -g argument of declare command

    declare -p hashTable testArray | sed 's/ -[aA]/&g/' >$File
    

    Nota: I prefer using sed when writting $File, instead of when reading.

    fn() { source $File; }
    
  2. declaring global variable out of the scope of function:

    declare -p hashTable testArray | sed 's/^.* -[aA] //' >$File
    

    then now:

    fn() { source $File; }
    declare -A hashTable
    declare -a testArray
    fn
    

    If Associative array are declared before function and declare command are not used in the scope of function, this will do the job.

2 Comments

Nota: source could by written .: fn() { . $File; }.
I also prefer injecting the -g switch on writing the file. I will use declare -p hashTable | sed '1s/^declare -[aA]/&g/' > $File to inject it only on the first line, and append the others the same way.

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.