What does this RANDOM-based command mean in bash?

时间:2015-09-14 15:33:22

标签: linux bash random

I'm using the RANDOM variable to generate a string that consists of 8 characters, but I don't fully understand how it works. The structure of the command is ${char:offset:length}:

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

Can someone explain how it works? Especially RANDOM%${#char}? What do % and # mean in this case?

1 个答案:

答案 0 :(得分:6)

Walk through it step by step:

$ echo ${#char}
12

This returned the length of the char string. It's documented in the bash manpage in the "Parameter expansion" section.

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

This performs a modulus (%) operation on RANDOM. RANDOM is a bash special variable that provides a new random value each time it is read. RANDOM is documented in the "Shell variables" section; 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.