What is the 'function' keyword used in some bash scripts?

前端 未结 3 955
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 07:05

For example: Bash-Prog-Intro-HOWTO

function foo() {}

I make search queries in info bash and look in releted chapters of POSIX for

3条回答
  •  暖寄归人
    2020-11-28 07:53

    The function keyword is optional when defining a function in Bash, as documented in the manual:

    Functions are declared using this syntax:

    name () compound-command [ redirections ]

    or

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

    The first form of the syntax is generally preferred because it's compatible with Bourne/Korn/POSIX scripts and so more portable.
    That said, sometimes you might want to use the function keyword to prevent Bash aliases from colliding with your function's name. Consider this example:

    $ alias foo="echo hi"
    $ foo() { :; }
    bash: syntax error near unexpected token `('
    

    Here, 'foo' is replaced by the text of the alias of the same name because it's the first word of the command. With function the alias is not expanded:

     $ function foo() { :; }
    

提交回复
热议问题