gpt4 book ai didi

bash - 使用圆括号而不是大括号定义 bash 函数体

转载 作者:行者123 更新时间:2023-11-29 08:52:52 25 4
gpt4 key购买 nike

这个脚本演示了用括号定义一个 bash 函数带括号的诗句。括号有很好的效果我猜是在函数“local”中创建的环境变量因为函数体是作为子 shell 执行的。输出是:

A=something
A=
B=something
B=something

问题是这是否允许用于定义函数的语法。

#!/bin/bash

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

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

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

最佳答案

是的,该语法是允许的。如 bash man page 中所述,一个 bash 函数的定义是:

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

更多描述(也来自手册页):

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.

(){} 括起来的列表是复合命令。完整列表(再次来自手册页,只是编辑成一个简单的列表):

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 - 使用圆括号而不是大括号定义 bash 函数体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14651980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com