Variable substitution in a for-loop using {$var}
I'm very new to bash scripting and I'm trying to practice by making this little script that simply asks for a range of numbers. I would enter ex. 5..20 and it should print the range, however - it just echo's back whatever I enter ("5..20" in this example) and does not expand the variable. Can 开发者_如何学Gosomeone 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
- Brace expansion in bash does not expand parameters (unlike zsh)
- You can get around this through the use of
eval
and command substitution$()
eval
is evil because you need to sanitize your input otherwise people can enter ranges likerm -rf /;
andeval
will run that- Don't use the
function
keyword, it is not POSIX and has been deprecated - use
read
's-p
flag instead of echo
However, for learning purposes, this is how you would 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 the use of eval
is OK because you are only echo
'ing the range
One way is to use eval
,
crude example,
for i in $(eval echo {0..$range}); do echo $i; done
the other way is to use bash's C style for
loop
for((i=1;i<=20;i++))
do
...
done
And the last one is more faster than first (for example if you have $range > 1 000 000)
One way to get around the lack of expansion, and skip the issues with eval is to use command substitution and seq.
Reworked function (also avoids globals):
function func_print_range
{
for n in $(seq $1 $2); do
echo $n
done
}
func_print_range $start $end
Use ${}
for variable expansion. In your case, it would be ${range}. You left off the $ in ${}, which is used for variable expansion and substitution.
精彩评论