Search code examples
bashterminaldeclare

Shall I define a function using declare built-in?


When listing all the defined functions on the system the name of each function is prepended with declare -f:

bash4.3 declare -F | head
declare -f __expand_tilde_by_ref
declare -f __get_cword_at_cursor_by_ref
declare -f __git_eread
...

As a proof of concept I am trying to define a function as:

bash4.3 declare -f 'count() { ls -1 | wc -l; } '
bash4.3 declare -F | grep -w count
bash4.3 count() { ls -1 | wc -l; }
bash4.3 declare -F | grep -w count
declare -f count

In the output above, only definition that is recognized when function defined without declare. Do I understand correct that declare built-in is not used for function declaration?


Solution

  • This is not legal. From https://wiki.bash-hackers.org/commands/builtin/declare, under the table of error codes:

    +-------------+--------------------------------------------+
    | Exit status | Reason                                     |
    +-------------+--------------------------------------------+
    | != 0        | Attempting to define a function using `-f` |
    +-------------+--------------------------------------------+