开发者

not evalute variables before runtime in for loop

Is there any hack to not evaluate variables in bash before runtime? I have a kind of for loop like this: the problem is i have it inside a 开发者_JAVA百科echo... otherwise this works great!

for i in $(seq 0 100); do echo $(echo $RANDOM % 10 | bc); done

the result is for example always 3...


Beside your problem: your solution uses 2 external processes, 1 pipe, 1 subprocess for a trivial exercise. Pure Bash:

for (( CNTR=0; CNTR<=100; CNTR+=1 )); do
  echo  $((RANDOM%10))
done


This works for me.

for i in $(seq 0 100);

do
    echo $RANDOM % 10 | bc
done

I see ... with echo this works for me:

for i in $(seq 0 100);

do
    echo "foo $(echo $RANDOM % 10 | bc)"
done


Alternatively, a brace expansion could be used:

for i in {0..100}; do
  echo $((RANDOM%10))
done


The traditional solution when you want to preempt variable interpolation is to use quoting and eval. This is not as elegant as a pure-Bash solution, but obviously more portable.

 for i in $(seq 0 100); do
   eval 'echo $RANDOM % 10 | bc'
 done

This is just a minimal refactoring of your original code, and I post it only for completeness.


You have a couple of problems here and I don't think either of them have to do with variable evaluation.

The first is that $RANDOM isn't defined here. Maybe you have it set to 3 somewhere and that's why you always get 3 as output?

The second is that you don't need both those echos. Omit the outer one, along with the $() around the other one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜