Search code examples
linuxbashlocal

in bash what does the -n parameter in "local -n" mean?


in bash what does the -n parameter in local -n var... mean? - how does it differ from local var...

I can't find a good example / explanation for it. There are no man pages for keywords (it seems?). The closest I have found is a comment here: local: -n: invalid option - which suggests something about not using ! param expansion


Solution

  • Parameters to local are unfortunately not documented in help local, but in help declare:

     `-n` make NAME a reference to the variable named by its value
    

    How does it work?

    #! /bin/bash
    f () {
        local -n x=y
        y=12
        x=42
        echo $x $y  # 42 42
    }
    f
    

    You can achieve similar behaviour with the ! indirection (that's what the comment in the linked question means):

    #! /bin/bash
    f () {
        x=y
        y=12
        echo ${!x}  # 12
    }
    f