f1="filename1";
i=1;
c=f$i
echo $c
What shell command should I use so that echo $c
returns "filename1" as the output?
f1="filename1";
i=1;
c=f$i
echo $c
What shell command should I use so that echo $c
returns "filename1" as the output?
Use variable indirection.
#!/bin/bash
f1="filename1";
i=1;
c=f$i
echo ${!c}
It works in bash ( GNU bash, version 4.1.2(1)-release ). I have not tried in other shells.
You can use eval
to "nest" variable substitutions.
f1="filename1";
i=1;
eval c=\${f$i}
echo $c
# Expand the variable named by $1 into its value. Works in both {ba,z}sh
# eg: a=HOME $(var_expand $a) == /home/me
var_expand() {
if [ -z "${1-}" ] || [ $# -ne 1 ]; then
printf 'var_expand: expected one argument\n' >&2;
return 1;
fi
eval printf '%s' "\"\${$1?}\""
}
It warns when given:
Avoid intensive operations like eval. Use an associative array.
#!/bin/bash
typeset -A c
c[f1]=filename1
i=1
echo ${c[f$i]}