Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable substitution in a for-loop using {$var}

Tags:

bash

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 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
like image 792
ZDRuX Avatar asked Mar 27 '11 04:03

ZDRuX


People also ask

What is variable substitution in TCL?

If a word contains a dollar-sign (``$'') then Tcl performs variable substitution: the dollar-sign and the following characters are replaced in the word by the value of a variable. Variable substitution may take any of the following forms: $name.

What is variable substitution Linux?

The name of a variable is a placeholder for its value, the data it holds. Referencing (retrieving) its value is called variable substitution.

What is a variable in substitution?

Variable substitutions are a flexible way to adjust configuration based on your variables and the context of your deployment. You can often tame the number and complexity of your variables by breaking them down into simple variables and combining them together using expressions.


2 Answers

  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

like image 73
SiegeX Avatar answered Oct 20 '22 17:10

SiegeX


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
like image 35
Morgen Avatar answered Oct 20 '22 17:10

Morgen