0

what is the "eval" doing in this script? What does this evaluate to?

#!/bin/bash    
n=1    
for i `eval echo {1..$1}`    
do    
   n=$((n * i))     
done
2
  • the backticks evaluate the expression; eval evaluates the curly braces which expand from 1 to $1 (argument of your function). I think that just for i in `echo {1..$1}` would do it. Commented Dec 14, 2013 at 0:51
  • Using eval is generally a bad thing. consider using seq instead: for i in `seq 1 $1`; do echo $i; done. Commented Dec 14, 2013 at 3:03

3 Answers 3

2

Eval executes the shell command that it finds in its arguments. You need to do this because the .. operator requires its arguments to be literal numbers, not variables.

eval echo {1..$1}

first substitutes the value of $1 into the argument as part of normal variable substitution. If the argument to the script was 5, this becomes:

eval echo {1..5}

Then eval executes that command, so it executes:

echo 1 2 3 4 5

Since this is all inside backticks, the output of the echo is substituted into the for line, so it becomes:

for i in 1 2 3 4 5
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that make a lot of sense!
2

To avoid confusion and the usage of eval you can use c-style for-loop:

for ((i=1; i<=$1; i++))

1 Comment

C language always makes more sense to me.
0

The eval echo {1..$1} generates a list of all numbers from 1 to the first argument. You then loop through all those values and multiply them to n, generating n!.

The {a..b} syntax generates a list of all the numbers from a to b, inclusive. You have to call eval because the .. syntax requires numbers, not variables - putting the eval allows variable substitution before running the command.

I also suspect that you wanted to write for i in `eval echo {1..$1}`, not for i `eval echo {1..$1}`, as the latter generates a syntax error.

2 Comments

Yes, I did forget the "in". Thanks for the explanation.
Re: "eval does variable substitution before it runs the command": This is true in general, but in this case there is no parameter substitution for it to do. The $1 is replaced with 5 before eval is even invoked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.