Multiple methods for random number implementation in Linux Shell (date, random, UUID)

Source: Internet
Author: User


In daily life, random numbers are often used. They want to drop dice, capture dice, and draw lots. It's easy to implement. So we are doingProgramIt's really not easy to design a random number through your own program. Currently, many operating system kernels provide corresponding APIs. These raw parameters are used to obtain original information about computer operations, such as memory, voltage, and physical signals, its value can be unique within a period of time. Okay, I will not talk about it. Haha.



What methods do we use to obtain random numbers in shell scripts?



 



1. Obtain a random number by time (date)



This is also frequently used. It can be said that time is unique and will not be repeated. We can obtain the unique value of the same time from this. Adapted to all programs.



Example:


[chengmo @ centos5 shell] $ date +% s
1287764773
#Get timestamp, currently until: 1970-01-01 00:00:00 seconds apart
#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, we use it as the random number base. Next we will see how to obtain the random number in a piece of data.


#! / bin / sh

#Write a random function, call the method random min max
#Get random integers directly at min and max
#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 through 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;


Check the running result:



[Chengmo @ centos5 shell] $ sh testrandom. Sh
1, 2-60, 5600
2, 2-average, 5295
-
4, 2-random, 3148
5, 2-random, 9041
6, 2-random, 4290
7, 2-hour, 2380
-
9, 2-random, 5474
-,



In a loop, the values are different.



This is a common method to adapt to various languages.AlgorithmEven if the server does not provide a unique data tag at a time point, we can use this method to create our own pseudo-random number. The following is a simpler method. Do not do it on our own.



2. Use internal system variables ($ random)


In fact, Linux already provides a system environment variable, which is a random number directly. Haha, I think it is a waste of time to learn this method !!

[chengmo @ centos5 shell] $ echo $ RANDOM
10918
[chengmo @ centos5 shell] $ echo $ RANDOM
10001

# 2 consecutive visits with different results, this data is an integer less than or equal to 5 digits

I may have doubts. How can I obtain a random number with more than five digits?

Add a fixed 10-digit integer and perform the remainder operation. The result is the same as that in Example 1. The next example is self-reliance.


3. generate random numbers (/dev/random, urandom) based on unique data in the system)



We know that under the dev directory, there are some default Linux devices. It gives us the feeling that the corresponding files are stored on the keyboard, hard disk, and optical drive. In fact, some Linux devices are very special and have special purposes. We mentioned earlier:/dev/[UDP | TCP]/host/port is special. Oh, it's a long journey.



The/dev/random device stores real-time data of the current operating environment of the system. It can be regarded as the unique value data at a time in the system, so it can be used as the random number metadata. We can read the data in a file. The device data of/dev/urandom is the same as that of random. However, it is a non-blocking random number generator, and read operations will not cause blocking.



Instance:


 



[chengmo @ centos5 shell] $ head -1 / dev / urandom
ãÅ † ù ... • KTþçanVÕã¹Û & ¡ õ¾ "ô2íùU" žF¦_ ÿ "† mEðûUráÏ = J¯TŸA • ÌAÚRtÓ

#Read a line, why is it garbled? In fact, it saves real-time data through binary data, so how do we turn it into integer data?


[chengmo @ centos5 ~ / shell] $ head -200 / dev / urandom | cksum
1615228479 50333
#Since urandom's data is very large, it cannot be read directly by cat. Here, the first 200 rows are taken. In fact, the entire data is changed, and how much is taken is unique.
#cksum will read the contents of the file, and generate unique integer data. As long as the contents of the file are not changed, the generated result will not change.

[chengmo @ centos5 shell] $ head -200 / dev / urandom | cksum | cut -f1 -d ""
484750180
#cut with "" split, then get the first field data of the split


 



Obtain the integer data. Then, a method similar to one can obtain the random number. Topic: in the program, we often obtain the unique MD5 value, followed by a string. If you want to represent it as an integer, you can use the CRC function. CRC is a cyclic redundancy check. When the same data is computed, a string of integer data is obtained. Currently, this verification is widely used. For more information, see CRC.



The following method reads the generated UUID from the device.



 



4. Read the uuid code of Linux



Before that, there was a concept: What is UUID?



UUID code full name isUniversal Unique Identifier(Universally unique identifier, UUID), which is a standard for software construction andFree Software Foundation(Open Software Foundation, OSF) is organized inDistributed Computing Environment(Distributed computing environment, DCE.



 



UUID PurposeIt enables all elements in a distributed system to have unique identification information without specifying the identification information through the central control terminal. In this way, each user can create a uuid that does not conflict with others. In this case, duplicate names are not required during database creation. It will make the uuid generated by any computer on the network be unique across the internet server network. The original information is added to hardware, time, and current running information of the machine.



The UUID format is:It contains 32 16-digit numbers, and the "-" connection number is divided into five segments, in the format of 8-4-4-12 32 characters. Example: 550e8400-e29b-41d4-a716-446655440000. Therefore, the theoretical total number of UUID is 216x8 = 2128, which is approximately 3.4x1038. That is to say, if 1 mb uuid is generated every second, it takes 10 billion years to use up all UUID.



In fact, you must have heard of The GUID (Globally Unique Identifier) Code, which is similar to UUID and supported by Microsoft. The code here is basically generated by the operating system kernel. In Windows, you can easily obtain the uuid code, regardless of the database or other software.



 



UUID in Linux



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


[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 


 



This is a common integer method of active random numbers in Linux. Apart from the first method, the last three methods have different pseudo data sources that generate random codes, which are related to the/dev/Random Device. They are different. If you have other methods, please share them with you.


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.