简体   繁体   中英

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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