Defining bash function body using parenthesis instead of braces

前端 未结 2 1556
攒了一身酷
攒了一身酷 2020-12-19 02:23

This script demonstrates defining a bash function with parenthesis verses with braces. The parenthesis have the nice effect of making environment variables created in the f

2条回答
  •  臣服心动
    2020-12-19 02:57

    Both are valid, and as Carl mentioned any compound command can also be used, e.g.:

    $ f() if [ "$1" = 'a' ]; then echo 'equals a'; fi
    $ f a
    equals a
    $ f b
    $
    

    POSIX 7 2.9.5 Function Definition Command http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_05:

    The format of a function definition command is as follows:

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

    [...] The argument compound-command represents a compound command, as described in Compound Commands.

    Then 2.9.4 Compound Commands http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04:

    (compound-list) [...] Variable assignments and built-in commands that affect the environment shall not remain in effect after the list finishes.

    { compound-list;} Execute compound-list in the current process environment.

    The semantics are the same as using () without a function definition: it does not create a new process, but gets executed in what POSIX and Bash call a "subshell environment".

提交回复
热议问题