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?

9
  • 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.
    – user313992
    Mar 13, 2020 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.
    – user313992
    Mar 13, 2020 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. Mar 13, 2020 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 Mar 13, 2020 at 17:46
  • 1
    I am confused. What are you trying to do? Edit the question to give a simple minimal But less abstract example. Mar 13, 2020 at 20:00

0

You must log in to answer this question.

Browse other questions tagged .