Separar namespaces para funções e variáveis em shells POSIX

12

No traço, as funções e as variáveis parecem viver em namespaces separados:

fn(){
    fn="hello world"
}
fn; echo "The value is $fn!" #prints: The value is hello world!
fn; echo "The value is $fn!" #prints: The value is hello world!
#the fn variable doesn't conflict with the fn function

Este é um recurso específico do traço ou uma garantia POSIX?

    
por PSkocik 30.10.2016 / 09:48

2 respostas

13

Uma garantia :

2.9.5 Function Definition Command

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 function is named fname; the application shall ensure that it is a name (see XBD Name) and that it is not the name of a special built-in utility. An implementation may allow other characters in a function name as an extension. The implementation shall maintain separate name spaces for functions and variables.

    
por 30.10.2016 / 11:45
8

Variáveis e funções residem em diferentes namespaces em dash e isso também é especificado por POSIX :

The implementation shall maintain separate name spaces for functions and variables.

Além disso, as variáveis têm escopo global, por padrão. Algumas shells (por exemplo, bash, ksh e zsh) fornecem a palavra-chave local para declarar variáveis em uma função apenas com escopo local.

Então, sim, o comportamento que você está vendo é garantido pelo POSIX.

POSIX não tem padronizado local , ainda :

The description of functions in an early proposal was based on the notion that functions should behave like miniature shell scripts; that is, except for sharing variables, most elements of an execution environment should behave as if they were a new execution environment, [..]

[..] Local variables within a function were considered and included in another early proposal (controlled by the special built-in local), but were removed because they do not fit the simple model developed for functions and because there was some opposition to adding yet another new special built-in that was not part of historical practice. Implementations should reserve the identifier local (as well as typeset, as used in the KornShell) in case this local variable mechanism is adopted in a future version of this standard.

(ênfase minha)

    
por 30.10.2016 / 10:17