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

前端 未结 3 951
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  -上瘾入骨i
    2020-11-28 07:48

    The function keyword is necessary in rare cases when the function name is also an alias. Without it, Bash expands the alias before parsing the function definition -- probably not what you want:

    alias mycd=cd
    mycd() { cd; ls; }  # Alias expansion turns this into cd() { cd; ls; }
    mycd                # Fails. bash: mycd: command not found
    cd                  # Uh oh, infinite recursion.
    

    With the function keyword, things work as intended:

    alias mycd=cd
    function mycd() { cd; ls; }  # Defines a function named mycd, as expected.
    cd                           # OK, goes to $HOME.
    mycd                         # OK, goes to $HOME.
    \mycd                        # OK, goes to $HOME, lists directory contents.
    

提交回复
热议问题