Variable substitution in for-loop using {$ var}

I am very new to bash scripts and I am trying to practice by creating this little script that just asks for a range of numbers. I would introduce ex. 5..20, and it should print a range, however - it just responds to what I type ("5..20" in this example) and does not expand the variable. Can someone tell me what I'm doing wrong?

Script:

echo -n "Enter range of number to display using 0..10 format: " read range function func_printrage { for n in {$range}; do echo $n done } func_printrange 
+7
source share
4 answers
  • Bracket extension in bash does not expand parameters (unlike zsh)
  • You can get around this with eval and substituting the $() commands
  • eval is evil because you need to sanitize your input, otherwise people may enter ranges such as rm -rf /; and eval will run this
  • Do not use the function keyword, it is not POSIX and is deprecated
  • use read -p flag instead of echo

However, for training, here is how you do it:

 read -p "Enter range of number to display using 0..10 format: " range func_printrange() { for n in $(eval echo {$range}); do echo $n done } func_printrange 

Note. In this case, using eval OK, because you are only echo 'in the range

+15
source

One way is to use eval , a crude example,

 for i in $(eval echo {0..$range}); do echo $i; done 

another way is to use a bash C style for loop

 for((i=1;i<=20;i++)) do ... done 

And the latter is faster than the former (for example, if you have a range of $ 1,000,000)

+6
source

One way to get around the lack of an extension and skip problems with eval is to use command substitution and seq.

Redesigned function (also excludes global variables):

 function func_print_range { for n in $(seq $1 $2); do echo $n done } func_print_range $start $end 
+5
source

Use ${} to expand variables. In your case, it will be $ {range}. You stopped $ in $ {}, which is used to expand variables and replace.

-one
source

All Articles