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:
[[email protected] shell] $ date +% s1287764773 # Get timestamp, current to: 1970-01-01 00:00:00 the number of seconds apart # If you use it for random numbers, the same data for one second is the same. In the loop processing, multi-threaded inside the basic can not meet the requirements. [[email protected] shell] $ Date +% n738710457 # Get nanosecond data for the current time, accurate to one-seconds. # This is quite Precise, even in multi-CPU, a lot of loops inside, the same second inside, it is difficult to have the same results, but there will be a lot of repeated collisions at different times [[email protected] shell] $ date <Code class = "Bash plain"> +% s% n1287764807051101270 # This can be said to be more perfect, added a timestamp, plus nanoseconds
Using it to make a base of random numbers, let's see how to get a random number in a piece of data.
#! / bin / sh # Write a random function and call the method random min max # to get a random integer directly between min and max # copyright chengmo QQ: 8292669 # Get the random number return value, and update the value after calculating the random number in the shell function functionrandom () {min = $ 1; max = $ 2- $ 1; num = $ (date +% s +% N); ((retnum = num% max + min)); #Remainder operation can be 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, read outside} # to get 1-10 seq data items foriin {1. .10}; do out = $ (random 2 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!!
123456 |
[[email protected] shell]$echo$RANDOM10918[[email protected] shell]$echo$RANDOM10001#连续2次访问,结果不一样,这个数据是一个小于或等于5位的整数 |
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:
|
[[email protected] shell] $ head-1 / dev / urandom ??? ù ...? KTt? anV ?? 1? & ??? "? 2íùU"? F | _? "? mEe? Urá? = JˉT? A? ÌAúRtó # Reading 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? [[Email protected] ~ / shell] $ head-200 / dev / urandom | cksum1615228479 50333 # Since the data of urandom is very large, it cannot be read directly by cat. Here we take the first 200 rows. In fact, the entire data is changed, and the number is the same. #cksum will read the file Content, the only integer data is generated, only the file content is unchanged, the generated result will not change, and the php crc function [[email protected] shell] $ head-200 / dev / urandom | cksum | cut-f1 -d "484750180 # cut with" "to split, and then get the first field data of the 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.
|
[[email protected] ~ / shell] $ cat / proc / sys / kernel / random / uuiddff68213-b700-4947-87b1-d9e640334196 [[email protected] ~ / shell] $ cat / proc / sys / kernel / random / uuid7b57209a -d285-4fd0-88b4-9d3162d2e1bc # After 2 consecutive readings, the uuid obtained is different. [[email protected] ~ / shell] $ cat / proc / sys / kernel / random / uuid | cksum | cut-f1 -d "" 2141807556 # Same as above to get random integers |
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.
"Go" Linux shell implements random number of methods (DATE,RANDOM,UUID)