Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this RANDOM-based command mean in bash?

Tags:

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?

like image 943
Dimareal Avatar asked Apr 11 '26 04:04

Dimareal


1 Answers

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.

like image 100
JB. Avatar answered Apr 13 '26 04:04

JB.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!