What are the parentheses used for in a bash shell script function definition like “f () {}”? Is it different than using the “function” keyword?

后端 未结 3 914
灰色年华
灰色年华 2020-12-28 12:21

I\'v always wondered what they\'re used for? Seems silly to put them in every time if you can never put anything inside them.

function_name () {
    #stateme         


        
相关标签:
3条回答
  • 2020-12-28 12:51

    The keyword function has been deprecated in favor of function_name() for portability with the POSIX spec

    A function is a user-defined name that is used as a simple command to call a compound command with new positional parameters. A function is defined with a "function definition command".

    The format of a function definition command is as follows:

    fname() compound-command[io-redirect ...]
    

    Note that the { } are not mandatory so if you're not going to use the keyword function (and you shouldn't) then the () are necessary so the parser knows you're defining a function.

    Example, this is a legal function definition and invocation:

    $ myfunc() for arg; do echo "$arg"; done; myfunc foo bar
    foo
    bar
    
    0 讨论(0)
  • 2020-12-28 12:51

    The empty parentheses are required in your first example so that bash knows it's a function definition (otherwise it looks like an ordinary command). In the second example, the () is optional because you've used function.

    0 讨论(0)
  • 2020-12-28 13:10

    Without function, alias expansion happens at definition time. E.g.:

    alias a=b
    # Gets expanded to "b() { echo c; }" :
    a() { echo c; }
    b
    # => c
    # Gets expanded to b:
    a
    # => c
    

    With function however, alias expansion does not happen at definition time, so the alias "hides" the definition:

    alias a=b
    function a { echo c; }
    b
    # => command not found
    # Gets expanded to b:
    a
    # => command not found
    unalias a
    a
    # => c
    
    0 讨论(0)
提交回复
热议问题