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?
typeset -p | cut
useprintf %q
(see the update to my A to your previous Q. Eg.repr() { repr() { printf -v "$1" %q "$2"; }
to use asrepr varname string
:repr q "e's f"; echo "$q"
=>e\'s\ f
. – Mar 13 '20 at 16:18declare -n
):set_to_13(){ declare -n v=$1; v=13; }; set_to_13 var; echo "$var"
=>13
. – Mar 13 '20 at 16:20unset v
it will unset var and leave v defined. You erase the nameref withunset -n v
. – Paul_Pedant Mar 13 '20 at 17:02declare
inside a function makes it local). – ilkkachu Mar 13 '20 at 18:00local -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