Linux shell implementation random several methods of sharing (DATE,RANDOM,UUID) _linux shell

Source: Internet
Author: User
Tags uuid


In daily life, random numbers are actually often encountered, want to throw dice, lottery, and draw lots. Oh, very simple can be achieved. So in doing programming, really to design a random number through their own program that is really not easy. Now a lot of the operating system kernel will provide the appropriate API, these raw parameters are to get some computer to run the original information, such as memory, voltage, physical signal, etc., its value in a time period can be guaranteed to be unique. All right, I won't say any more nonsense. Oh.



Shell scripting What do we have that gets the random number method?



One, through time to obtain random number (date)



This is what we often use, it can be said that time is the only, and will not repeat, from the inside to get the unique value of the same time. Adapt to all the programs inside.



Example:


[Chengmo @ centos5 shell] $ date +% s
1287764773
#Get timestamp, current to: 1970-01-01 00:00:00 seconds apart
#If use it to do random numbers, the same second data is the same. In doing cyclic processing, multithreading inside the basic can not meet the requirements.
[Chengmo @ centos5 shell] $ date +% n
738710457
#Get nanosecond data for the current time, accurate to one-seconds.
#This is quite accurate, even in multiple CPUs, a large number of loops inside, the same second, it is difficult to have the same results, but at different times there will be a lot of repeated collisions
[Chengmo @ centos5 shell] $ date +% s% n
1287764807051101270
#This can be said to be more perfect, added timestamp, plus nanosecond


By the above instructions, use it to do the base of random numbers, and then we see how to get a piece of data how to obtain random numbers.


#! / bin / sh
#Write a random function, call method random min Max
# 在 min and Max get random integers directly
#copyright chengmo qq: 8292669
#Get the random number return value, after calculating the random number in the Shell function, update the value
function random ()
{
min = $ 1;
max = $ 2- $ 1;
num = $ (date +% s +% n);
((Retnum = num% max + min));
#Perform the remainder operation
echo $ retnum;
#Here by echo print out the value, and then get the function, stdout can get the value
#There is a return, define the full price variable, and then the function to change the contents of the outside Read
}
#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 of the operation:



[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



Within a loop, the values are different.



This is our common method, to adapt to various languages, is a common algorithm, even if the server does not provide, at some point the same unique data markers, we can also use this method to do their own pseudo-random number. Here's a simpler way to do it.



2. Through internal system variables ($RANDOM)



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


[Chengmo@centos5 shell]$ echo $RANDOM
10918
[chengmo@centos5 shell]$ echo $RANDOM
10001
#2 consecutive visits , the result is not the same, this data is an integer less than or equal to 5 bits


There may be doubt, if more than 5 digits of random number how to get it?



Oh, add a fixed 10-bit integer, and then the remainder, as in the case of 1. The next example is our self-reliance.



3, through the system's unique data Generation random number (/dev/random,urandom)



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



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



Instance:


[Chengmo @ centos5 shell] $ head-1 / dev / urandom ãå † ù ... ktþçanvõã¹û & ¡ õ¾ 'ô2íùu' žf¦_ÿ '† meðûuráï = j¯tÿa ìaúrtó
# 读 行, how is garbled? In fact, it is through the binary data to save real-time data, then how do we turn it into integer data?
[Chengmo @ centos5 ~ / shell] $ Head-200 / dev / urandom | Cksum
1615228479 50333
#Since the data of urandom is very much, can not directly through the cat read, here take the first 200 lines, in fact, the whole data is changed, take how much is the same as the only.
#cksum will read the contents of the file, generate a unique representation of the integer data, only the file content unchanged, the results will not change, and PHP CRC function
[Chengmo @ centos5 shell] $ Head-200 / dev / urandom | Cksum | Cut-f1-d ""
484750180
#cut "", and then get the first field data split


The integer data is obtained, and then a similar method can be obtained to a random number. Digression: In the program, we often MD5 get a unique value, and then the string, if you want to represent the integer mode, you can pass the CRC function. CRC is a cyclic redundancy check, the same data through the operation, will get a series of integer data. This validation is now widely used. Detailed to understand, you can 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, what is a UUID?



The full name of the UUID code is a universal unique identifier (universally unique Identifier, UUID), a standard for software construction, and an organization of the Free Software Foundation (Open Software Foundation, OSF) in a distributed computing environment (Distributed Computing Environment, DCE) a part of the field.






The purpose of 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. In this way, each person can create a UUID that does not conflict with others. In such cases, there is no need to consider the problem of name duplication when database creation occurs. It makes the UUID code generated by any computer on the network unique to the entire network of Internet servers. Its original information will be added to the hardware, time, machine current running information and so on.



The UUID format is: Contains 32 16 digits, with a "-" connection number divided into five paragraphs, in the form of 8-4-4-4-12 32 characters. example; 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 to say, it takes 10 billion years to run out of all the UUID if 1 trillion UUID is generated per nanosecond.



In fact, when you do database design, certainly heard, GUID (globally unique identifier) code, it is actually similar to the UUID, supported by Microsoft. Here coding, basically has the operating system kernel to produce. As you can remember, it's easy to get this UUID code in Windows, whether it's a database or other software.






The UUID code for Linux



The Linux UUID code is also provided by the kernel, within the/proc/sys/kernel/random/uuid file. In fact, there are many other files in the random directory that 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 resulting UUID is different
[chengmo @ centos5 ~ / shell] $ cat / proc / sys / kernel / random / uuid | cksum | cut-f1-d ""
2141807556 <c8 /> #Same method to get random integer 


This is Linux below, several common active random number integer methods, in addition to the first is different, in fact, the latter 3, generating random code of pseudo data sources, are related to/dev/random equipment. It's just that they differ in their appearance. If you have any more options, please give me a message and share it 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.