开发者

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


  1. Brace expansion in bash does not expand parameters (unlike zsh)
  2. You can get around this through the use of eval and command substitution $()
  3. eval is evil because you need to sanitize your input otherwise people can enter ranges like rm -rf /; and eval will run that
  4. Don't use the function keyword, it is not POSIX and has been deprecated
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜