Bash braces are a bad replacement

It works:

echo ${!var_pointing_to_another_var}

It does not mean:

echo ${!${var}_string_suffix}

In other words, I have var, which consists of two parts: the first is another variable, the second is a string suffix. Together they form var, which points to another var. But I get a bad substitution error.

Due to readability and security issues, I want to avoid the eval command.

+4
source share
2 answers

as far as I know, this is the only way.

t="${var}_string_suffix"
echo "${!t}"
+5
source

http://mywiki.wooledge.org/BashFAQ/006

You probably need an associative array .

# The most common multi-dimensional array emulation for bash >= 4.0 is
# to use an associative array with delimiter.
typeset -A arr=([foo;bar]=test)
printf '%s\n' "${arr[$(printf '%q;%q' "$var1" "$var2")]}" # bash 4

${!var} , eval. eval , bash . wiki . "namerefs" - bash 4.3, .

var1=foo
var2=bar
foobar=test
ref=${var1}${var2}
printf '%s\n' "${!ref}" # print test (bash-only, <= 4.3)

# Note: not a great example of nameref usage
typeset -n ref2=${var1}${var2}
printf '%s\n' "$ref2" # bash >= 4.3 / ksh93 / mksh

# Correct eval usage
if [[ $ref == [a-zA-Z_]+([a-zA-Z0-9_]) ]]; then
    eval printf '%s\\n' "\${$ref}" # POSIX
    eval printf '%s\\n' "$(printf '${%q}' "$ref")" # bash / ksh93 / zsh
fi
+2

Source: https://habr.com/ru/post/1569255/


All Articles