Home > other >  What is the the use of declare command in initializing an array in bash?
What is the the use of declare command in initializing an array in bash?

Time:01-16

arr=("Jane Doe" "John Doe" "Janet")
declare -a arr=("Jane Doe" "John Doe" "Janet")

What is the difference between the two array initialization in bash?

CodePudding user response:

The two array initializations presented, supposing that they in fact are initializations (see below), mean exactly the same thing if the declare occurs at the top level. When declare is executed inside a function, however, without the -g option, it is equivalent to local, declaring a variable that is local to the function. On the other hand, the direct initialization declares a global variable regardless of where it appears.

example() {
  direct=(a b c)
  declare -a indirect=(d e f)

  #prints a
  echo "$direct"

  #prints d
  echo "$indirect"
}

example

#prints a
echo "$direct"

#prints nothing
echo "$indirect"

Of course, local would be clearer where the intention is in fact to declare a local variable. declare is more interesting in combination with others of its options, including when those are combined with -a. Consider declare -a -r foo=(1 2 3), for example.


At the beginning, I raised the possibility that one or both of the commands in question might not be an "initialization". Here I am drawing a distinction between initialization, which defines an initial value for a variable that did not previously exist, and assignment, which changes the value of a variable that already does exist. If I had been particularly careful then I would have noted that although the declare version contains an initialization, the overall command is not well characterized as an initialization.

This brings forward another distinction between the two commands in question:

  • the direct assignment version serves as an initialization of a new (global) variable only if neither a global nor an in-scope local variable with the given name already exists. Where a variable with the given name does exist, it is merely an assignment. On the other hand,
  • an initialization in a declare command serves only as an initialization. If the declared variable already exists then any initial value specified via the declare command is ignored.

CodePudding user response:

arr=("Jane Doe" "John Doe" "Janet")
declare -a arr=("Jane Doe" "John Doe" "Janet")

Both of the above statements can be used to create an array. The second one with the declare command provides readability in declaring arrays.

Elaboration on that here: https://stackoverflow.com/a/19742842/13798537

  •  Tags:  
  • Related