Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!

like image 503
user3526905 Avatar asked Nov 01 '25 12:11

user3526905


1 Answers

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.

like image 71
Tom Fenech Avatar answered Nov 03 '25 02:11

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!