0

With this function:

repr() {
    declare -p $1 | cut -d '=' -f 2- > /tmp/.repr
    $1=$(</tmp/.repr)
    rm /tmp/.repr
}

It gives an error message, when I write:

repr test

This see the argument as string:

repr() {
    declare -p 'test' | cut -d '=' -f 2- > /tmp/.repr
    'test'=$(</tmp/.repr)
    rm /tmp/.repr
}

And not as name:

repr() {
    declare -p test | cut -d '=' -f 2- > /tmp/.repr
    test=$(</tmp/.repr)
    rm /tmp/.repr
}

How can I solve the problem?

ctrl-alt-delor
  • 27,473
  • 9
  • 58
  • 102
  • Instead of `typeset -p | cut` use `printf %q` (see the update to my A to your previous Q. Eg. `repr() { repr() { printf -v "$1" %q "$2"; }` to use as `repr varname string`: `repr q "e's f"; echo "$q"` => `e\'s\ f`. –  Mar 13 '20 at 16:18
  • 2
    In general, you can pass variable by names via references (`declare -n`): `set_to_13(){ declare -n v=$1; v=13; }; set_to_13 var; echo "$var"` => `13`. –  Mar 13 '20 at 16:20
  • Be aware that the nameref persists: if you `unset v` it will unset var and leave v defined. You erase the nameref with `unset -n v`. – Paul_Pedant Mar 13 '20 at 17:02
  • printf -v bar %q "$foo" in the function is read like: printf -v 'bar' %q "$foo", but despite this, it continues to work. Thank you very much – Riccardo La Marca Mar 13 '20 at 17:46
  • @Paul_Pedant, no need to explicitly unset the nameref if it's just used inside that function (`declare` inside a function makes it local). – ilkkachu Mar 13 '20 at 18:00
  • See also: [Is it possible to print the content of the content of a variable with shell script? (indirect referencing)](https://unix.stackexchange.com/q/452723/170373), [get environment variable by variable name?](https://unix.stackexchange.com/q/251893/170373), [Use a variable reference “inside” another variable](https://unix.stackexchange.com/q/41406/170373) – ilkkachu Mar 13 '20 at 18:03
  • @ilkkachu Didn't know that, but it is pretty mucky. `local -n` also declares a nameref. `declare -g -n` makes the reference global. `local - ` gives a function a local copy of the shell args that it can modify. Too many special rules around! – Paul_Pedant Mar 13 '20 at 19:54
  • 1
    I am confused. What are you trying to do? Edit the question to give a simple minimal **But less abstract** example. – ctrl-alt-delor Mar 13 '20 at 20:00
  • https://stackoverflow.com/questions/13716607/creating-a-string-variable-name-from-the-value-of-another-string – s3n0 Mar 13 '20 at 22:57

0 Answers0