0

I need to set a variable name from a string. Here is my code :

var="cle"
value="1"

printf -v $var "$value"

echo $cle

I want it to output "1"

I am getting:

illegal option "-v"

I tried to replace printf by the declare function but, dash doesn't include it either.

DevNico
  • 3
  • 2

1 Answers1

0

The only way to do this in dash is to use eval, but that is risky unless you know that your string is a valid identifier.

expr "$var" : '[_[:alpha:]][_[:alnum:]]\{0,\}$' && eval "$var=$value"

The call to expr fails (or at least, is intended to fail) if the value of var is anything other than a single valid identifier.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks. `expr`outputs me the string length of `$var`. If I only enter `eval $var=$value"`, it works perfectly. I don't think the check might be necessary. – DevNico Apr 13 '17 at 13:41
  • You can redirect the output of `expr` to `/dev/null` to ignore it; the important thing is that the exit status will be non-zero if the match fails, preventing `eval` from running. This avoids nasty surprises with something like `var="rm -rf /"`. – chepner Apr 13 '17 at 13:50