-1

I am trying to set a local variable in a function with nameref.

The script code is the following:

#!/usr/bin/bash
msg=hello
myparam=''

superfunc () {
productfile=$1
local -n refmyparam=$2
}

superfunc $msg $myparam
echo $myparam

When running it I get the error:

 line 7: local: `': not a valid identifier

We use GNU bash, version 5.2.21

1 Answer 1

2

local -n and declare -n need a variable name as their value, not its value.

Also, creating a local reference variable doesn't change the original variable. You need to change the reference variable to see how the change propagates back to the original:

#!/bin/bash
msg=hello
myparam=''

superfunc () {
    productfile=$1
    local -n refmyparam=$2
    refmyparam=changed     # Modify the local variable.
}

superfunc $msg myparam     # No dollar sign for $2!
echo $myparam              # Changed!

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.