admin管理员组

文章数量:1384760

Is there a way to make new variables to be scoped locally by default in zsh?

I was thinking something like this:

setopt magic_local_opt;

x=1
function foo {
  x=2
}

echo $x

and then end goal would be to print '1'

Is there a way to make new variables to be scoped locally by default in zsh?

I was thinking something like this:

setopt magic_local_opt;

x=1
function foo {
  x=2
}

echo $x

and then end goal would be to print '1'

Share Improve this question edited Mar 18 at 16:31 Martin 3741 gold badge5 silver badges17 bronze badges asked Mar 18 at 16:24 Jan MatejkaJan Matejka 1,9901 gold badge15 silver badges33 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

use this:

function foo {
  typeset x=2  # Makes x local to the function
}

x=1
foo
echo $x  # This will print 1

Not by default. You would at least have to write something like

local x=2

Since it is easy to fet this and unwillingly create a global variable, you can put at least in your script at

setopt warn_create_global

This would at least produce an error message, if you create a new variable without explicitly declaring it as local or global. It would not help in your concrete example, because x has already a value

本文标签: Is there a way to make new variables to be scoped locally by default in zshStack Overflow