2

There is a 2 bash script file. First file b.sh is mentioned below.

#!/bin/bash
declare -a arr1=()
func() {
    var_a=12
    arr1[0]=20
    arr1[1]=30
    declare -a arr2=()
    arr2[0]=40
    arr2[1]=50
}

Second file a.sh is mentioned below.

#!/bin/bash
source b.sh
func
echo $var_a
echo ${arr1[1]}
echo ${arr2[1]}

Output is

12
30

My doubt is, why the local array variable (arr2) in func is not accessible in a.sh. But the local variable var_a is accessible.

4
  • 1
    @anubhava The question is about arr2 and var_a. Commented Jan 25, 2018 at 20:31
  • @rashok, why do you think var_a is a local variable? Commented Jan 25, 2018 at 21:05
  • BTW, this question could be simplified. There's no need to have two separate scripts and a source command to reproduce this problem -- it could easily be created with just one. Commented Jan 25, 2018 at 21:12
  • Ya true, It is a simplified version of the issue faced in an another script based test framework, which constains 2 script file. Commented Mar 4, 2018 at 17:59

1 Answer 1

5

arr2 is a local variable because it was created using declare. As stated in the Bash Manual:

When used in a function, declare makes each name local, as with the local command, unless the -g option is used.

Since you didn't create var_a with declare, the assignment creates a global variable, so it's accessible outside the funtion. If you'd written:

declare var_a=12

or

local var_a=12

inside the function then it would have been local.

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

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.