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

Time:07-19

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

CodePudding user response:

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

CodePudding user response:

-n declares the variable to be a nameref:

A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see Bash Builtins) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. For instance, if a variable name is passed to a shell function as its first argument, running

declare -n ref=$1

inside the function creates a nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref, and changes to its attributes, are treated as references, assignments, and attribute modifications to the variable whose name was passed as $1.

It's worth noting that namerefs and -n were added in Bash 5.

  • Related