子外壳中对$ RANDOM的引用均返回相同的值 [英] References to $RANDOM in subshells all returning identical values

查看:72
本文介绍了子外壳中对$ RANDOM的引用均返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下简短脚本会打印一个随机的十位二进制数字:

The following short script prints a random ten-digit binary number:

#!/usr/bin/zsh
point=''
for i in `seq 1 10`
do
    echo $RANDOM >/dev/null
    point=$point`if [ $RANDOM -gt 16383 ]; then echo 0; else echo 1; fi`
done
echo $point

但是,如果我删除了似乎无用的echo $RANDOM >/dev/null行,该脚本将始终打印11111111110000000000.

However, if I remove the apparently useless echo $RANDOM >/dev/null line, the script always prints either 1111111111 or 0000000000.

为什么?

推荐答案

从手册页开始:

RANDOM的值形成一个有意重复的伪随机序列;引用的子壳 除非引用或播种RANDOM的值,否则RANDOM将导致相同的伪随机值 在子外壳调用之间的父外壳中.

The values of RANDOM form an intentionally-repeatable pseudo-random sequence; subshells that reference RANDOM will result in identical pseudo-random values unless the value of RANDOM is referenced or seeded in the parent shell in between subshell invocations.

echo的无用"调用提供了引用,该引用允许命令替换引起的子外壳每次生成不同的值.

The "useless" call to echo provides the reference that allows the subshell induced by the command substitution to produce a different value each time.

这篇关于子外壳中对$ RANDOM的引用均返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆