0

I am trying to print the values of a variable which has naming sequentially in bash.

boxes1=abcd boxes2=efgh boxes3=ijkl

for (( i=1; i<=$boxCount; i++ )); 
   do
     echo "\$$boxes{i}"
   done

I want output like: abcd efgh ijkl

ilkkachu
  • 138,973
  • For indexed variables, use arrays: https://mywiki.wooledge.org/BashGuide/Arrays For other cases where you have a variable name in another variable, namerefs (declare -n) or indirect refs (${!p}) – ilkkachu Aug 04 '21 at 16:58
  • I tried the above mentioned options, but it didn't work. Could you help further pls. – sandeep yashodha Shiviraju Aug 04 '21 at 21:35
  • Add the exact command you tried, and any error messages, to your question. Alternatively, ask a new question about the use of arrays, namerefs or indirect variables. Using a sequence of distinct names is not viable: every time you add another name in the series, you need to update (and test) significant amounts of code. See "Two or more, use a for", or possibly DRT (Don't repeat yourself). – Paul_Pedant Aug 04 '21 at 21:42
  • Below is the command and the error:

    for(( i=1; i<=3; i++ )); do declare -n var="boxes$i"; printf 'boxes%d = %s\n' "$i" "$var"; done -bash: declare: -n: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...] boxes1 = -bash: declare: -n: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...] boxes2 = -bash: declare: -n: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...] boxes3 =

    – sandeep yashodha Shiviraju Aug 04 '21 at 22:32
  • @sandeepyashodhaShiviraju You need to define boxes1 boxes2 boxes3 before you declare a nameref that references them. Also for (( i=1; i<=3; i++ )); do var=boxes$i; echo "${!var}"; done. – Paul_Pedant Aug 05 '21 at 23:13

0 Answers0