I just wanted to know what is the difference between:
echo {$number1..$number2}
AND
eval echo {$number1..$number2}
Of course, imagine that there is a value in $number1 and $number2. With the first option is just not working, but with the second option it works. I'm not the typical guy that only want something to work, I want to understand why it happens like that so, why exactly is this happening like this?
This and these are used to point to something near you. For a singular thing, use this. For a plural thing, use these.
We use this (singular) and these (plural) to talk about things close to us, and that (singular) and those (plural) to talk about things at some distance away from us.
The word these is used to denote more than one object that is near to the speaker. The word those is used to denote more than one object that is far from the speaker. It is used as a Pronoun.
$number1..$number2
is not a valid sequence expression, so the whole expression is left unchanged.{1..3}
(given that number1=1
and number2=3
).Your second example works the same, except that the result of variable expansion ({1..3}
) is passed to Bash again via eval
, giving brace expansion a second chance: 1..3
is a correctly formed sequence expression and therefore brace expansion yields the expected result:
1 2 3
eval
Using eval
should generally be avoided, as it easily introduces security problems: If number1
or number2
receive input and are not properly sanitized, malicious code can be injected into your program. See this related question for ways to replace eval
in various use cases.
In your specific example, the sequence could instead be created by a for loop combined with arithmetic evaluation:
for ((i=number1 ; i<=number2; i+=1)); do echo -n "$i" ; done | xargs
1 2 3
A popular non-Bash solution would be to use seq
(as pointed out by Walter A in his answer) as in seq "$number1" "$number2" | xargs
.
Note: xargs
joins multi-line output to a single line in these examples.
This answer to a related question gives more information on the topic.
Also, the EXPANSION section in the bash(1) manual page is pretty informative on sequence and workings of different expansion mechanisms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With