user3526905
user3526905

Reputation: 181

Local variable scope when one function calls another inside bash shell

# ! /bin/sh

function pqr()
{
  # This prints value to 10 even though variable is local inside a
  echo "Displaying value of var a $a"  
}
function abc()
{
local a=10
# call function pqr and don't pass value of a
pqr
}

Even though I don't pass variable a to pqr() function I get a=10 inside pqr(). My question is is scope and visibility of a is same inside pqr() as that of abc() ?Is this because we are calling pqr() from function abc()?I was expecting new variable would get created inside pqr and will display blank value.(As this is how variable scope and visibility works inside modern languages so I am curious how this works inside bash ) I understood that In the above example If I re declare a inside pqr() then new variable will get created and hence displaying blank value. Thanks in advance!!!

Upvotes: 4

Views: 1338

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74705

As mentioned in the comments (from man bash):

When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children.

So calling pqr from within abc means that the variable $a is visible inside both functions.

It's worth mentioning that since you're using bash-specific features such as local and the non-portable function syntax, you should change your shebang to #!/bin/bash.

Upvotes: 7

Related Questions