2

Is there a way to assign arbitrary values to dynamically named variables in pure shell (i.e. sh, not bash) without using eval?

I would like to know if there was a way to avoid using eval as it can allow for arbitrary code execution.

let seems only to work only for numerical values.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
rhlee
  • 3,857
  • 5
  • 33
  • 38
  • 1
    Could you clarify your requirements? The `declare` command in your accepted answer is not "pure shell", in that it is a `bash` extension, not part of POSIX `sh`. – chepner Oct 06 '14 at 16:13

1 Answers1

0

Give a try to declare: it allows you to specify variables on the fly.

v="test"
declare my$v="hello"
echo "$mytest"

Returns:

hello

You can find more info in man declare - I couldn't find a reference to the shell manual.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • @rhlee What did you mean by "pure shell"? `declare` is a `bash` extension, and not available in every POSIX-compatible shell. – chepner Oct 06 '14 at 15:53
  • @chepner better comment in the question, because rhlee won't get the notification here. – fedorqui Oct 06 '14 at 15:58
  • 1
    @chepner Yes I found out about the differences between pure and non-pure shells yesterday. The script ran fine on cygwin, but gave me `declare: not found` on linux. I came across https://wiki.ubuntu.com/DashAsBinSh , which told me to use `local` instead of `declare`. However I got `local: not in a function`, so I wrapped the whole script in a function and called it and everything worked. I think fedorqui's answer still counts as the correct one as I didn't specify a pure shell. – rhlee Oct 07 '14 at 15:19