![](/img/trans.png)
[英]What are the parentheses used for in a bash shell script function definition like “f () {}”? Is it different than using the “function” keyword?
[英]shell function definition with and without keyword
我花了很长时间才发现以下Shell脚本不起作用的原因:
if command -v z > /dev/null 2>&1; then
unalias z 2> /dev/null
z() {
[ $# -gt 0 ] && _z "$*" && return
cd "$(_z -l 2>&1 |
fzf --height 40% --nth 2.. --reverse --inline-info +s --tac \
--query "${*##-* }" |
sed 's/^[0-9,.]* *//')"
}
fi
是在这种情况下,函数定义需要function关键字function z() {...}
。 没有它,我得到:
~/.shell/functions:112: defining function based on alias `z'
~/.shell/functions:112: parse error near `()'
我找不到任何地方说在函数定义中使用或不使用function
关键字之间有任何区别。 为什么在这种情况下是解决方案? (我在zsh和bash中尝试过)
从Bash参考手册 :
读取命令时(而不是执行命令时),别名会扩展。
因此, z
在读取if
语句时而不是在执行时扩展。 因此,即使您unalias
别名,别名也已在if
语句中扩展(即z() ...
已扩展)。
添加function
很有用,因为仅当别名用作第一个单词时才对其进行扩展。 如果将function
添加到函数声明中,则不会扩展任何内容。
检查以下代码,该代码演示复合命令中别名的行为:
#!/usr/bin/env bash
shopt -s expand_aliases
alias greet='echo hello'
if true; then
unalias greet 2> /dev/null
#still outputs hello!
greet
#not first word, outputs greet
echo greet
fi
#error!
greet
此代码段显示别名foo
在执行之前确实已扩展。 结果,有一个叫做bar
的函数, 而不是 foo
:
$ alias foo='bar'
$ foo() { echo hello; }
$ declare -f foo
$ declare -f bar
bar ()
{
echo hello
}
#declaring with 'function' keyword will work as expected
$ function foo { echo hi; }
$ declare -f foo
foo ()
{
echo hi
}
《 Bash参考手册 》进一步详细解释了别名的行为,并建议采取以下措施:
为了安全起见,请始终将别名定义放在单独的行上,并且不要在复合命令中使用别名。
手册页(man bash)指出“保留字功能是可选的。”:
Shell函数定义Shell函数是一个像简单命令一样被调用并使用一组新的位置参数执行复合命令的对象。 Shell函数声明如下:
name () compound-command [redirection]
function name [()] compound-command [redirection]
This defines a function named name. **The reserved word function is optional.** If the function reserved word is supplied, the parentheses are optional.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.