我有以下行来产生一个随机数:
头-c 3 / dev / urandom | hexdump | sed -e's / [0 az] // g'| 头-c 1
这工作正常,但有时(很less)它返回一个新的行。 有谁知道这可能是为什么?
简短的回答:您的三个随机字节在hex中匹配[0a-f] +。
长答案:pipe道中的hexdump命令会返回一个地址偏移量,后跟一个空格和从head -c 3 /dev/urandom收到的三个字节的hex表示。 第一行的地址偏移量始终为“0000000”,因此被sedfilter丢弃,以及之后的空间。 所以在第一行中唯一相关的东西是sed命令是三个urandom字节的hex表示。 但是会发生(随机;-))所有三个字节的hex表示将只包含数字0和字符a到f 。 所以你的sedfilter将不会返回任何第一行,这留下了一个换行符。 pipe道末端的head -c 1将会从hexdump滤出下一行,所以你什么也看不到。
一个不是很随机的例子:
# First three bytes with values 4, 5 and 6 octal. $ echo -n $'\004\005\006' | hexdump 0000000 0504 0006 0000004 # Because of little endianess, we get the 5 back after the sed and head filters $ echo -n $'\004\005\006' | hexdump | sed -e 's/[0 az]//g' | head -c 1 5 # Now with FF bytes (be aware that it is octal notation), # only 'f' and '0' and space are left: $ echo -n $'\377\377\377' | hexdump 0000000 ffff 00ff 0000004 # Now filtering this through sed gives nothing back $ echo -n $'\377\377\377' | hexdump | sed -e 's/[0 az]//g' | head -c 1 $
@Iain写道,你应该使用$RANDOM 。
我不知道为什么你的命令正在产生一个新的线,但似乎非常复杂。 你有没有尝试使用bash内build$RANDOM ?
echo $(( $RANDOM % 9 ))
例如。
在堆栈溢出(Stack Overflow)中,还有很多显然不那么复杂的方法。