shell函数定义有和没有关键字

问题描述 投票:2回答:2

我花了很长时间才发现以下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 z() {...}。没有它,我得到:

~/.shell/functions:112: defining function based on alias `z'
~/.shell/functions:112: parse error near `()'

我找不到任何说明在函数定义中使用或不使用function关键字之间的任何区别。在这种情况下,为什么这是解决方案? (我试过zsh和bash)

bash shell zsh
2个回答
6
投票

来自Bash Reference Manual

读取命令时会扩展别名,而不会在执行时扩展别名。

因此,当读取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 Reference Manual更详细地解释了别名的行为,并建议如下:

为安全起见,请始终将别名定义放在单独的行中,并且不要在复合命令中使用别名。


0
投票

手册页(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.
© www.soinside.com 2019 - 2024. All rights reserved.