第85页 | Learning the Bash Shell | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

Local Variables in Functions

A local statement inside a function definition makes the variables involved all become local to that function. The ability to define variables that are local to "subprogram" units (procedures, functions, subroutines, etc.) is necessary for writing large programs, because it helps keep subprograms independent of the main program and of each other.

Here is the function from our last example with the variable var1 made local:

function afunc
{
  local var1
  echo in function: $0 $1 $2
    
  var1="in function"
  echo var1: $var1
}

Now the result of running ascript arg1 arg2 is:

var1: outside function
ascript: arg1 arg2
in function: ascript funcarg1 funcarg2
var1: in function
var1: outside function
ascript: arg1 arg2

Figure 4-3 shows the scope of each variable in our new script. Note that afunc now has its own, local copy of var1, although the original var1 would still be used by any other functions that ascript invokes.

Figure 4-3. Functions can have local variables

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库