Linux shell implements random number of methods (DATE,RANDOM,UUID)

Source: Internet
Author: User

In daily life, random numbers are actually often encountered, want to throw dice, lottery, and draw lots. Oh, very simple can be achieved. It's really not easy to design a random number in your own program. Now a lot of the operating system kernel will provide the corresponding API, these raw parameters are to get some computer running raw information, such as memory, voltage, physical signals and so on, its value in a time period can be guaranteed to be unique. All right, I'm not going to say a word. Oh.

Shell scripting do we have those methods of getting random numbers?

First, get random numbers by time (date)

This is what we often use, we can say that time is unique, and will not repeat, from this inside to obtain the same time unique value. Adapted to all the programs inside.

Example:

1[Email protected] shell]$Date+%s2 12877647733#获得时间戳, current to:1970- on- on xx:xx:xxnumber of seconds apart4 #如果用它做随机数, the same data for one second is the same. In the loop processing, multi-threaded inside the basic can not meet the requirements. 5  6[Email protected] shell]$Date+%N7 7387104578 #获得当前时间的纳秒数据, accurate to one-seconds. 9 #这个相当精确了, even in multi-CPU, a large number of cycles inside, the same second inside, it is difficult to have the same results, but there will be a lot of repeated collisions at different timesTen   One[Email protected] shell]$Date+%s%N A 1287764807051101270 -#这个可以说比较完美了, added time stamp, plus nanosecond

Using it to make a base of random numbers, let's see how to get a random number in a piece of data.

1#!/bin/SH2  3 #写个随机函数, calling method random min Max4 #在min get random integers directly from Max5#copyright Chengmo QQ:82926696  7  8 #获得随机数返回值, the value is updated after the random number is calculated in the Shell function9 functionrandom ()Ten { Onemin=$1; Amax=$2-$1; -num=$ (Date+%s+%N); -((retnum=num%max+min)); the #进行求余数运算即可 -     Echo$retnum; - #这里通过echo Print out the value, and then get the function, stdout can get the value - #还有一种返回, define the full price variable, and then the function changes the contents, read outside + } -   +#得到1-10 SEQ Data item A  forIinch{1..Ten}; at  Do  -out=$ (random2 10000); -     Echo$i,"2-10000", $out; -  Done;

Look at the results of the operation:

[Email protected] shell]$ sh testrandom.sh
1,2-10000,5600
2,2-10000,5295
3,2-10000,3432
4,2-10000,3148
5,2-10000,9041
6,2-10000,4290
7,2-10000,2380
8,2-10000,9009
9,2-10000,5474
10,2-10000,3664

Within a loop, the resulting values are different.

This is our common method, adapt to a variety of languages, is a general algorithm, even if the server does not provide, at some point the same unique data marker, we can also use this method to do their own pseudo-random number. Here's an easier way to do it, don't let us do it ourselves.

2. Through internal system variables ($RANDOM)

In fact, Linux has provided a system environment variables, is directly random number, haha, think just learning method, is not in vain!!

1 [[email protected]  echo  $RANDOM2109183 [[email] Protected]  echo  $RANDOM4100015  6 # 2 consecutive accesses, the result is not the same, this data is an integer less than or equal to 5 bits


It may be doubtful if the number of random numbers more than 5 bits is available.

Oh, add a fixed 10-bit integer, and then to seek redundancy, as in Example 1. The next example is our self-reliance.

3. Generate random Numbers (/dev/random,urandom) by unique data within the system

We know the dev directory below, is Linux some of the default devices, it gives us the feeling is to put the keyboard, hard disk, CD-ROM and other devices of the corresponding files. In fact, some Linux equipment is very special, has a special purpose. We said earlier:/dev/[udp|tcp]/host/port is more special. Oh, it's far away.

A/dev/random device that stores real-time data about the environment in which the system is currently running. It can be thought of as the system's unique value data at some point, so it can be used as a random-number meta-data. We can read the data in the file read mode. /dev/urandom This device data is the same as in random. Only, it is a non-blocking random number generator, and the read operation does not cause blocking.

Instance:

1[Email protected] shell]$Head-1/dev/Urandom2ãå†ù... Ktþçanvõã¹û&¡õ¾ "Ô2íùu"? F¦_ÿ "†meðûuráï=j¯tÿa Ìaúrtó3  4 #读一行, how is garbled? It's actually saving real-time data from binary data, so how do we turn it into integer data? 5  6  7[Email protected] ~/shell]$Head- $/dev/urandom |cksum8 1615228479 503339 #由于urandom的数据是非常多, can not be read directly through cat, here take the first 200 lines, in fact, the entire data is a change, take how much is the same is unique. Ten #cksum will read the contents of the file, generate a unique representation of the integer data, only the contents of the file unchanged, the resulting results will not change, with the PHP CRC function One   A[Email protected] shell]$Head- $/dev/urandom | Cksum |Cut-f1-d" " - 484750180 -#CutSplit and then get the first field data to be split


Get the integer data, and then a method like one can get to the random number. Digression: In the program, we often MD5 get unique values, and then the string, if you want to represent an integer mode, you can pass the CRC function. CRC is cyclic redundancy check, the same data through the operation, will get a string of integer data. This validation is now widely used. For more information, refer to: CRC.

Here's another way to read the generated UUID code directly from the device.

4, read the Linux UUID code

Before mentioning this, there is a concept of what is a UUID?

The UUID code is the Universal Unique identifier (universally unique Identifier, UUID), it is a software construction standard, also for the Free Software Foundation (Open Software Foundation, OSF) is part of the organization in the field of distributed computing Environments (distributed Computing Environment, DCE).

The purpose of the UUID is to allow all elements in a distributed system to have unique identifying information, without the need to specify the identification information through the central control terminal. In this way, everyone can create a UUID that does not conflict with others. In such a case, there is no need to consider the name duplication problem when the database was created. It makes the UUID code generated by any computer on the network, which is the only one on the Internet throughout the server network. Its original information will be added hardware, time, machine current operation information and so on.

The UUID format is: contains 32 16 digits, with "-" connection number is divided into five segments, in the form of 8-4-4-4-12 32 characters. 550e8400-e29b-41d4-a716-446655440000, so: The total number of UUID in theory is 216 x 8=2128, approximately equal to 3.4 x 1038. That is, if you produce 1 trillion uuid per second, it will take 10 billion years to run out of all the UUID.

In fact, we do database design time, must have heard, GUID ( global Unique identifier ) code, it is actually similar to the UUID, supported by Microsoft. This code is basically generated by the operating system kernel. It's easy to get this UUID code in Windows, whether it's a database or any other software, you remember.

The UUID code of Linux

The UUID code of Linux is also provided by the kernel, in/proc/sys/kernel/random/uuid this file. In fact, the random directory, there are many other files, are related to the generation of UUID.

1[Email protected] ~/shell]$Cat/proc/sys/kernel/random/UUID2dff68213-b700-4947-87b1-d9e6403341963[Email protected] ~/shell]$Cat/proc/sys/kernel/random/UUID47b57209a-d285-4fd0-88b4-9D3162D2E1BC5 #连续2次读取, the resulting UUID is different.6  7[Email protected] ~/shell]$Cat/proc/sys/kernel/random/uuid| Cksum |Cut-f1-d" "8 21418075569#同上方法得到随机整数


This is Linux below, several common activity random number integer method, in addition to the first is different, in fact, after 3, generate random code of pseudo-data source, are related to/dev/random device. It's just that they differ in their presentation. If you have more options, please send me a message and share it with you.

Linux shell implements random number of methods (DATE,RANDOM,UUID)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.