简体   繁体   English

这个基于RANDOM的命令在bash中意味着什么?

[英]What does this RANDOM-based command mean in bash?

I'm using the RANDOM variable to generate a string that consists of 8 characters, but I don't fully understand how it works. 我正在使用RANDOM变量生成一个由8个字符组成的字符串,但是我不完全了解它的工作原理。 The structure of the command is ${char:offset:length} : 该命令的结构为${char:offset:length}

char="1234abcdABCD"
echo -n ${char:RANDOM%${#char}:8}

Can someone explain how it works? 有人可以解释它是如何工作的吗? Especially RANDOM%${#char} ? 特别是RANDOM%${#char}吗? What do % and # mean in this case? 在这种情况下, %#是什么意思?

Walk through it step by step: 逐步进行操作:

$ echo ${#char}
12

This returned the length of the char string. 这返回了char字符串的长度。 It's documented in the bash manpage in the "Parameter expansion" section. 它在bash联机帮助页的“参数扩展”部分中进行了说明。

$ echo $(( RANDOM % 12 ))
11
$ echo $(( RANDOM % 12 ))
7
$ echo $(( RANDOM % 12 ))
3

This performs a modulus ( % ) operation on RANDOM . 这将对RANDOM执行模数( % )操作。 RANDOM is a bash special variable that provides a new random value each time it is read. RANDOM是一个bash特殊变量,每次读取时都会提供一个新的随机值。 RANDOM is documented in the "Shell variables" section; RANDOM记录在“ Shell变量”部分; modulus in the "Arithmetic evaluation" section. “算术评估”部分中的模数。

$ echo ${char:0:8}
1234abcd
$ echo ${char:4:8}
abcdABCD
$ echo ${char:8:8}
ABCD

This performs substring extraction. 这将执行子字符串提取。 It's documented in the "Parameter expansion" section. 它记录在“参数扩展”部分。

Putting it all together: 放在一起:

$ echo -n ${char:RANDOM%${#char}:8}

This extracts up to 8 characters of the char string, starting at a random position in the string. 这提取到的8个字符char字符串,起始于字符串中的随机位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM