1

How can I access a variable with another variable, like this?

varAble="Hello"
varA="\n"
varBable="World"
varB="END"

for part in A, B
do
    echo var${part}ble
    echo var${part}
done
# Expect 'Hello\nWorldEND'
2

3 Answers 3

1

If you're using a modern version of bash you can use variable indirection:

varAble="Hello"
varA="\n"
varBble="World"
varB="END"

for part in A B
do
    for var in "var${part}ble" "var${part}"
    do
      printf '%s' "${!var}"
    done
done

The inner loop constructs a value in ${var} which is itself a variable name. Then the printf command prints the variable whose name is in ${var}.

1
  • Doesn't have to be that modern even, ${!p} is supported in at least Bash 3.2. Namerefs came later in 4.something. Commented Jul 8, 2024 at 16:01
0

You can first concatenate the text to reach the result and then print it using a code like this:

#!/bin/bash

varAble="Hello"
B="A"

eval echo \$var${B}ble

take a look at The 'eval' command in Bash and its typical uses for a better understanding on eval

0

You can store the name of the variables in an intermediate variable:

#! /bin/bash

varAble="Hello"
varA="\n"
varBble="World"
varB="END"
res=''

for part in A B; do
    var="var${part}ble"
    var2="var${part}"
    res="${!var}${!var2}"
done

echo "$res"

Results in

Hello\nWorldEND

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.