1
FICH10=primero.sh
FICH20=segundo.sh

for i in 10 20
do
   echo $FICH($i)  # I want resolved first $i and then resolver var FICH10
done

I want it to first solve $i and concatenate it to the FICH shoreline and thus return the value of $FICH10 or $FICH20 but without having to put the numbers, but they are resolved by the loop

I don't solved with the response asocciate

$ for i in 10 20
> do
> echo $((FICH$i))
> done
ksh: line 3: primero: parameter not set
1
  • Voters: the "duplicate" solutions work for bash, but this question is tagged as ksh and they do not work here Sep 9, 2020 at 21:26

2 Answers 2

3

Use variable indirection:

#!/bin/bash
fich10=primero.sh
fich20=segundo.sh

for i in 10 20 ; do
    var=fich$i
    echo ${!var}
done

Note I used small caps for variable names as they aren't system variables.

2
  • Thank you $ for i in 10 20 > do > var=fich$i > echo ${!var} > done but It does not work. That code gets the name of the variable, not its content. result of your code var var I don't need that, I need the content of the variables Sep 2, 2020 at 16:04
  • @LinuxVariable: What shell do you use to run it? It works for me in bash.
    – choroba
    Sep 2, 2020 at 16:43
2

With bash versions 4.3+, you can use a "nameref":

for i in 10 20; do
    declare -n var="FICH$i"
    echo "$var"
done

We can use eval to force a second round of variable substitutions, but as you can see, that's not required. eval is generally considered too dangerous to use for most cases.

2
  • Thank's you but It does not work. That code gets the name of the variable, not its content. result of your code FICH10 FICH20 I don't need that, I need the content of the variables. Sep 2, 2020 at 16:01
  • Are you omitting the -n flag? Take note of my caveat about the needed bash version. Sep 2, 2020 at 21:49

Not the answer you're looking for? Browse other questions tagged .