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'
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}.
${!p} is supported in at least Bash 3.2. Namerefs came later in 4.something.
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
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
varBble="World"?