1

I've a big question today ! I've made a little exemple of my situation.

FOO="foo";
fooBAR="final";

var=${${FOO}BAR}
echo $var

I want to print "final". I tried all sort of things like ${${!FOO@}BAR} (I know it's not correct) and I didn't found any solution to my problem. Ideally I don't want to pass via temporary variable/eval.

  • what is the problem with eval ? – Archemar Nov 25 '16 at 14:40
2

There will have to be some runtime code evaluation in any case

eval "var=\${${FOO}BAR}"
printf '%s\n' "$var"

Or without the temporary var:

eval "printf '%s\n' \"\${${FOO}BAR}\""

If your worry is that $FOO may contain other things than a variable name (like foo=$(reboot) which could have bad consequences), you'd want to do the sanitizing by hand before hand like:

valid_variable() {
  local LC_ALL=C
  case $1 in
    ("" | *[![:alnum:]]* | [0-9]*) return 1
  esac
}

valid_variable "${FOO}BAR" || exit 1
eval "printf '%s\n' \"\${${FOO}BAR}\""

With zsh, you could do:

printf '%s\n' ${(P):-${FOO}BAR}}

but you'd still want to sanitize the value of $FOO if it's not trusted as values like x[0$(reboot)] would still be a problem.

0

It was for passing argument to an other function, the best way i found :

local CLIENT_URL="${CLIENT}_URL"
local CLIENT_FOLDER="${CLIENT}_FOLDER"
local CLIENT_BIN_PATH="${CLIENT}_BIN_PATH"
installClient   ${UPDATE_OS_PACKAGES}\
                ${USER_NAME}\
                ${GROUP_NAME}\
                ${!CLIENT_URL}\
                ${!CLIENT_FOLDER}\
                ${!CLIENT_BIN_PATH}

This was for this reason I doesn't wanted to use temporary var or eval. (Sorry to answer 2 weeks after.)

-1

try

var=${FOO}BAR
## to print
eval echo \$$var
## to set
somevar=$(eval echo \$$var)
  • 1
    You're missing quotes. Here twice for each of those eval commands. Once for the eval command (for $var), and another time for the resulting echo command (for its $fooBAR variable). eval "echo \"\${$var}\"" – Stéphane Chazelas Nov 25 '16 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.