ast: local keyword is not recognized in a function

Rerpoducer script:

test_func() {
    local stat=$(< /proc/self/stat)
    echo $stat
}

test_func

Running this script gives this error :

 local: local can only be used in a function

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 16 (8 by maintainers)

Most upvoted comments

I’ll point out a few things about the local keyword:

  1. There’s a request to the Austin Group (the POSIX folks) about standardizing it as part of POSIX which has garnered a lot of comments in favor. ksh has typically been capable of running POSIX commands, so it may be worthwhile to implement for that reason.
  2. Debian requires all shells that can be used as /bin/sh to implement local (and they don’t build with SHOPT_BASH). Consequently, it isn’t possible to use ksh as /bin/sh on a Debian or Ubuntu system.
  3. Git requires a shell providing local in order to run the testsuite and shell commands. Consequently, it isn’t possible to use ksh as the shell for Git.
  4. All other open source POSIX-compliant shells that I’m aware of implement local: bash, dash, mksh, pdksh (and derivatives, like OpenBSD’s ksh), and zsh.

The first three would necessitate an implementation outside of SHOPT_BASH. Now, nothing requires that ksh fit these niches; it may be that folks prefer to preserve historical behavior over adding local, and that’s fine. But if there’s a desire to fill these use cases, then local should probably be implemented as a standard feature.

@hlangeveld This is consistent with my understanding as well. func()-style functions behave as sh, function func-style functions support things like local.

IIRC The AST group subscribed strongly to the idea of one interface, one name, one behaviour. When introducing new behaviour they would go out of their way to create a new interface with a new name.

From what I remember when typeset was introduced, the function keyword was created precisely for supporting local variables. The AST group did not want to “contaminate” old sh style functions with different behaviour, so a new type of function was created.

Interestingly, it works correctly if the function is defined using the function keyword.