KSH和bash脚本的区别 [英] Difference between ksh and bash script

查看:471
本文介绍了KSH和bash脚本的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider the following script (arithmetic syntax that is used for local_var2 is irrelevant for this case):

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

在运行它产生以下输出:

When run it produces the following output:

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

(其不是预期!)

(which is not what is expected!)

如果我运行在bash同一个脚本,输出是:

If I run the same script in bash, the output is:

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

(这是预期!)

推荐答案

这是的怪事 ksh93的之一。

排版变量婷界定其范围为本地只能与函数定义方式:

typesetting of variables to define their scope as local only works with the function definition style:

function func_name
{
}

不能与函数定义方式:

Not with the function definition style:

func_name()
{
}

随着 FUNC_NAME()的风格,一切都是全球性的。因此, KSH 的行为是按预期!

With the func_name() style, everything is global. So the behaviour of ksh is as expected!!!

庆典 KSH 明确理智的在这方面。因此它设置的变量两种功能作为当地的范围时,排版使用了。

But bash is clearly saner than ksh in this regard. So it sets the scope of variables in both functions as local when typeset was used.

KSH 文档中的条目,表明该函数defintions的区别是:

There's FAQ entry in ksh documentation stating the difference between the function defintions:

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.

这篇关于KSH和bash脚本的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆