Bash Script – for i in {x..y} [Duplicate]

bashprogrammingscripts

i am writing a script in bash and I would like to give the two numbers in the brackets, x and y to be precise, as variables.

I wrote the script this way:

echo "x?"
read x
echo "y"
read y

for i in {$x..$y}

but it does not work.

How could I set it up to make it function?

Thanks a lot in advance.

Best Answer

Use this simple bash solution:

for ((i=$x;i<=$y;i++))

Before using the following functions, read below !

For a sequence of numbers, you might use seq:

for i in $(seq $x $y)

If you really need brace expansion, you can use eval:

for i in $(eval echo {$x..$y})

Disclaimer:
eval is evil. This case is a perfect example: If the user writes $(do_something_evil) instead of a number, do_something_evil will be executed. So before using eval, make sure your input is not evil. The same applies to seq $x $y.

If you still want to use one of these functions, test the user input, which is generally a good idea: How do I test if a variable is a number in Bash?