Search code examples
bashindirection

Print multiple bash variables


I have the following script.

#!/bin/bash
d5=me
d6=you
d7=re

for i in {5..7}
do
    echo $"d$i"
 done

This prints out
d5
d6
d7

I'm looking to print
me
you
re


Solution

  • You can use "${!varName}" to reference value stored in varName variable:

    for i in {5..7}; do v="d$i"; echo "${!v}"; done
    me
    you
    re
    

    Check indirect variable expansion in bash

    Or even simpler:

    for v in d{5..7}; do echo "${!v}"; done
    me
    you
    re