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

Source: Internet
Author: User
Tags uuid
In daily life, random numbers are often encountered, and I want to throw dice, scratch, and draw lots. Hehe, it's very simple. So when doing programming, it is really not easy to design random numbers through your own program. Many of the operating system kernels now provide corresponding APIs. These original parameters are used to obtain some computer running original information, such as memory, voltage, physical signals, etc., and their values can be guaranteed to be unique within a time period. Well, I won't say nonsense. Ha ha.

   Shell script programs do we have those methods to get random numbers?

 

First, get random numbers by time (date)

This is also often used by us. It can be said that time is unique and will not be repeated. From this, the unique value of the same time is obtained. Adapted to all programs inside.

example:

[chengmo @ centos5 shell] $ date +% s
1287764773
1970-01-01 00:00:00 The number of seconds apart: # obtain a timestamp, the current
#If you use it for random numbers, the data for the same second is the same. When doing loop processing, the multi-threading basically cannot meet the requirements.
 
[chengmo @ centos5 shell] $ date +% N
738710457
#Get nanosecond data for the current time, accurate to one hundredth of a second.
#This is quite accurate. Even in multiple CPUs and a large number of loops, the same result is difficult to appear in the same second, but there will be a lot of repeated collisions at different times
 
[chengmo @ centos5 shell] $ date +% s% N
1287764807051101270
#This can be said to be perfect, adding a timestamp and adding nanoseconds
 

Through the above description, use it to make the cardinality of random numbers. Next, let's see how to get random numbers in a piece of data.

#! / bin / sh
 
# Write a random function, call the method random min max
# Max and min in random integers directly
#copyright chengmo QQ: 8292669
 
 
#Get the random number return value, update the value after calculating the random number in the shell function
function random ()
{
    min = $ 1;
    max = $ 2- $ 1;
    num = $ (date +% s +% N);
    ((retnum = num% max + min));
    #Perform the remainder operation
    echo $ retnum;
    #Here, print out the value by echo, and then get the value of the function, stdout can get the value
    #There is a return, define the full price variable, and then the function changes the content and reads outside
}
 
#Get 1-10 seq data items
for i in {1..10};
do
    out = $ (random 2 10000);
    echo $ i, "2-10000", $ out;
done;
Look at the results:

[Chengmo @ centos5 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

A cycle which give different values.

This is the method we used to meet a variety of languages, is a general-purpose algorithm, even if the server is not available, a unique data tag the same time, we can in this way, to do their own pseudo-random number. Here there's an easier way to do that, do not we ourselves do.

2, through an internal system variables ($ the RANDOM)

In fact, linux already provides a system environment variables, and direct that the random number, ha ha, I feel just learning, it is not in vain! !!


[Chengmo @ centos5 shell] $ echo $ RANDOM
10918
[Chengmo @ centos5 shell] $ echo $ RANDOM
10001
 
# 2 consecutive visits, the results are not the same, the data is less than or equal to a 5-bit integer
It may be questioned, and if more than five random numbers how to get it?

Oh, plus 10 fixed integer, then remainder, the same as with Example 1. The following is an example of self-reliance we do.

3, the unique data within the system generates a random number (/ dev / random, urandom)

We know that dev directory, linux is some default device, it gives us the feeling that put the keyboard, hard disk drives and other devices of the corresponding file. In fact, I linux some very special equipment, special purpose. Speaking in front of us: / dev / [udp | tcp] / host / port special bar. Oh, pull away.

/ Dev / random device, real-time data system stores the current operating environment. It can be seen as a system, when a unique value data, and therefore can be used as a random number of metadata. We can read the way through the file, read the data inside. / Dev / urandom inside the device as random data. But, it is non-blocking random number generator, a read operation does not produce blocking.

Example:


[chengmo @ centos5 shell] $ head -1 / dev / urandom
ãÅ † ù ... • KTþçanVÕã¹Û & ¡ õ¾ "ô2íùU" žF|_ ÿ "† mEðûUráÏ = J¯TŸA • ÌAÚRtÓ
 
# Read a line, how garbled it? In fact, it is saved in real time data of binary data, how do we turn it into integer data it?
 
 
[chengmo @ centos5 ~ / shell] $ head -200 / dev / urandom | cksum
1615228479 50333
# Because urandom data is very large, can not be directly read by cat, here take the first 200 lines, in fact, the entire data is changed, how much to take too unique.
#cksum will read the contents of the file, generates a unique integer data representation, only the file contents remain unchanged, it will not change the results generated with php crc function
 
[chengmo @ centos5 shell] $ head -200 / dev / urandom | cksum | cut -f1 -d ""
484750180
#cut with "" division, then the field data to obtain a first divided
 

Integer data obtained, and then, a similar approach can get the random number. Topic: a program which, md5 we often get a unique value, then the string, if you want to be represented as an integer, it can be .crc by crc cyclic redundancy check function, the same string of data obtained by calculation, will integer data. This verification is now a very wide application. To understand the details, you can refer to: crc.

Here there is a method to read directly from the device code generating good uuid.

 

4, the read linux code uuid

Prior to mention this, there is a concept that uuid what is it?

The full name of UUID code is Universally Unique Identifier (UUID). It is a software construction standard. It is also an organization of the Open Software Foundation (OSF) in the Distributed Computing Environment (DCE). ) a part of the field.

 

UUID aim is to make all the elements of a distributed system, can have a unique identification information, the identification information of the designated end do not need to be controlled by the center. In this way, everyone can create a UUID does not conflict with other people. In this case, you do not need to repeat the question when considering the name of the database creation. It will make any uuid network code generated by a computer, the Internet is the only entire server network. It will be added to the original hardware information, time, current machine operating information and so on.

The UUID format is: 32 hexadecimal digits, divided into five segments by "-" connection number, and 32 characters in the form of 8-4-4-4-12. Example: 550e8400-e29b-41d4-a716-446655440000, so: The theoretical total number of UUIDs is 216 x 8 = 2128, which is approximately 3.4 x 1038. In other words, if 1 trillion UUIDs are generated every nanosecond, it will take 10 billion years to exhaust all UUIDs.

In fact, when you are doing database design, you must have heard of the guid (Globally Unique Identifier) code, which is similar to uuid and is supported by Microsoft. The encoding here is basically generated by the operating system kernel. Everyone remember to get this uuid code in windows, no matter the database or other software.

 

uuid code for linux

Linux uuid code is also provided by the kernel, in the file / proc / sys / kernel / random / uuid. In fact, the random directory, and many other files in it, are related to generating uuid.


[chengmo @ centos5 ~ / shell] $ cat / proc / sys / kernel / random / uuid
dff68213-b700-4947-87b1-d9e640334196
[chengmo @ centos5 ~ / shell] $ cat / proc / sys / kernel / random / uuid
7b57209a-d285-4fd0-88b4-9d3162d2e1bc
#Read 2 times in a row, the uuid obtained is different
 
[chengmo @ centos5 ~ / shell] $ cat / proc / sys / kernel / random / uuid | cksum | cut -f1 -d ""
2141807556
#Same method as above to get random integers

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.