【问题标题】:Difference between ksh and bash scriptksh 和 bash 脚本之间的区别
【发布时间】:2014-06-26 13:02:43
【问题描述】:

考虑以下脚本(用于 local_var2 的算术语法与这种情况无关):

#!/bin/ksh

function my_func1
{
   typeset local_var1=one
   typeset local_var2
   (( local_var2 = 1 ))
   echo my_func1: local_var1 = $local_var1, local_var2 = $local_var2
}

my_func2()
{
   typeset local_var1=two
   typeset local_var2
   (( local_var2 = 2 ))
   echo my_func2: local_var1 = $local_var1, local_var2 = $local_var2
}
local_var1=0
local_var2=0
echo before functions: local_var1 = $local_var1, local_var2 = $local_var2

my_func1
echo after my_func1: local_var1 = $local_var1, local_var2 = $local_var2

my_func2
echo after my_func2: local_var1 = $local_var1, local_var2 = $local_var2

运行时会产生以下输出:

before functions: local_var1 = 0, local_var2 = 0
my_func1: local_var1 = one, local_var2 = 1
after my_func1: local_var1 = 0, local_var2 = 0
my_func2: local_var1 = two, local_var2 = 2
after my_func2: local_var1 = two, local_var2 = 2

(这不是预期的!)

如果我在 bash 中运行相同的脚本,输出是:

before functions: local_var1 = 0, local_var2 = 0
my_func1: local_var1 = one, local_var2 = 1
after my_func1: local_var1 = 0, local_var2 = 0
my_func2: local_var1 = two, local_var2 = 2
after my_func2: local_var1 = 0, local_var2 = 0

(这是预期的!)

【问题讨论】:

  • 测试并确认输出!虽然,除了说 ksh 很烂之外,我对此没有任何解释 ;-)
  • 在代码中使用set -vx(每个函数取决于shell),您会看到变量的内容与第一次使用第二次调用时的预期明显不同

标签: bash ksh


【解决方案1】:

这是ksh93 的怪异之处之一。

typesetting 变量以将其范围定义为本地仅适用于函数定义样式:

function func_name
{
}

不具有函数定义风格:

func_name()
{
}

使用func_name() 样式,一切都是全局的。所以ksh的行为符合预期!!!

bash 在这方面显然比ksh 更理智。因此,当使用typeset 时,它将两个函数中的变量范围设置为本地。

在 ksh 文档中有 FAQ 条目说明了函数定义之间的区别:

Q18. What is the difference between function name and name()?

A18. In ksh88 these were the same.  However, the POSIX standard
    choose foo() for functions and defined System V Release 2
    semantics to them so that there are no local variables
    and so that traps are not scoped.  ksh93 keeps the ksh88
    semantics for functions defined as function name, and
    has changed the name() semantics to match the POSIX
    semantics.  Clearly, function name is more useful.

【讨论】:

    【解决方案2】:

    根据this answer 中的描述,您很可能正在运行ksh 的AT&T 版本,其中typeset 内置函数使变量局部仅在使用function 关键字声明的函数中

    【讨论】:

      猜你喜欢
      • 2013-01-19
      • 1970-01-01
      • 2014-09-09
      • 2013-07-31
      • 2012-12-18
      • 1970-01-01
      • 2011-09-03
      • 2011-12-13
      相关资源
      最近更新 更多