2

This is what I want to achieve:

Function:

Func1() {
   $1="Hello World"
}

Call function:

local var1
Func1 var1
echo $var1  (should echo Hello World)

I found this example which seems to work, but I guess using eval is not a good idea:

Func1() {
   eval $1=$str1
}

How would be the correct way of doing this?

I'm coming from .Net and often use a parameter as a reference. For example, assigning a value back to the parameter which then can be used later on.

In the above example var1 should be assigned "Hello World"

(I'm using sh shell)

7
  • In bash, you could use variable indirection instead..
    – heemayl
    Jul 15 '16 at 17:13
  • 1
    what are you trying to achieve with this? are you just experimenting to see what it does? or do you have some purpose in mind? if the latter, then see xyproblem.info - my brain's a bit dull and tired at the moment, but i can't think of any use for this that can't be done better in several different ways.
    – cas
    Jul 16 '16 at 10:51
  • I just ran into a function with this design and I liked it. I was not able to dig deeper in how it was achieved....so I just go curious (I'm new to Linux shell and learning)
    – MrCalvin
    Jul 17 '16 at 10:37
  • @MrCalvin: If you just saw an example using it, you could always use it but it's not a good idea. Neither is using eval which most often leads to unexpected errors and security issues. Sep 5 '16 at 4:41
  • Just change my example code, I hope it's more clear now.
    – MrCalvin
    Sep 6 '16 at 13:34
1

eval is fine if you use it properly:

Func1() {
  eval "$1=\$str1"
}

Is safe as long as Func1 is only called with the variable names you intend it to be passed.

As always, you need to quote your variables. And here, $str1 doesn't need to be expanded before being passed to eval.

If Func1 may be passed arbitrary strings that are not under your control, then that's where you'd get issues with values like reboot;foo and need to sanitize it like:

Func1() {
  case $1 in
    "" |\
    *[!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]* |\
    [0123456789]* |\
    BASH* | LD_* | PATH | IFS | ENV | SHELLOPTS | PERL5LIB | PYTHON_PATH |...)
      echo >&2 "Can't set that variable"
      return 1
  esac
  eval "$1=\$str1"
}

Coming up with a complete list of problematic variables is a doomed task though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.