使用括号代替括号的定义bash函数体 [英] Defining bash function body using parenthesis instead of braces

查看:245
本文介绍了使用括号代替括号的定义bash函数体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本脚本演示了定义具有括号bash函数
经文用大括号。括号有做的不错的效果
在函数中创建环境变量本地,我猜
因为函数主体作为子壳执行。输出是:

  A =东西
A =
B =东西
B =东西

的问题是,如果这是允许的语法定义的函数。

 #!/斌/庆典富()(
    出口A =东西
    回声A = $ A
)栏(){
    出口B =东西
    回声B = $ B
}富
回声A = $ A
酒吧
回声B = $ B


解决方案

是的,语法是允许的。正如 庆典手册页,bash函数的定义是:

  [功能]名称()复合命令[重定向]

一些更多的描述(也从该名男子页):


  

功能的主体是复合命令复合命令。该命令通常是命令之间的名单 {} ,但可能会在复合所列的任何命令命令以上。


() {} 封闭名单是复合命令。完整名单(再次从该名男子页,刚编辑到一个简单的列表):


  

一个复合命令是以下之一:

 (名单)
{名单; }
((如pression))
[前pression]
对于名称[字]。 do列表; DONE
为((表达式1;表达式2;表达式3)); do列表; DONE
选择名称[中字]。 do列表; DONE
在[[案字(]图案[|图案] ...)列表;; ] ... ESAC
如果名单;然后列出; [ELIF清单;然后列出; ] ... [其他名单; ]科幻
而名单; do列表; DONE
直到名单; do列表; DONE


This script demonstrates defining a bash function with parenthesis verses with braces. The parenthesis have the nice effect of making environment variables created in the function "local", I guess because the function body is executed as a sub-shell. The output is:

A=something
A=
B=something
B=something

The question is if this is allowed syntax for defining a function.

#!/bin/bash

foo() (
    export A=something
    echo A=$A
)

bar() {
    export B=something
    echo B=$B
}

foo
echo A=$A
bar
echo B=$B

解决方案

Yes, that syntax is allowed. As described in the bash man page, the definition of a bash function is:

[ function ] name () compound-command [redirection]

Some more description (also from the man page):

The body of the function is the compound command compound-command. That command is usually a list of commands between { and }, but may be any command listed under Compound Commands above.

() and {} enclosed lists are compound commands. The full list (again from the man page, just edited down to a simple list):

A compound command is one of the following:

(list)
{ list; }
((expression))
[[expression]]
for name [ in word ] ; do list ; done
for (( expr1 ; expr2 ; expr3 )) ; do list ; done
select name [ in word ] ; do list ; done
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
while list; do list; done
until list; do list; done

这篇关于使用括号代替括号的定义bash函数体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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