Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random string in bash?

My goal is to have something like this in bash:

str=random_string(n scharacters)

I have managed to do the following:

chars=abcdefghijklmnopqrstuvwxyz
for (( i=1; i<=n; i++ ))
do
   str="${chars:RANDOM%${#chars}:1}"
done

The problem is that str also contains new lines.

Do you have any ideas?

like image 951
PanD22 Avatar asked Oct 29 '25 15:10

PanD22


1 Answers

This might be what you're looking for:

#!/bin/bash

chars='abcdefghijklmnopqrstuvwxyz'
n=10

str=
for ((i = 0; i < n; ++i)); do
    str+=${chars:RANDOM%${#chars}:1}
    # alternatively, str=$str${chars:RANDOM%${#chars}:1} also possible
done

echo "$str"

Your code was almost correct, except that you've missed the += operator. The += operator appends to the variable’s (str here) previous value. This operator was introduced into bash with version 3.1. As an aside note, it can also be applied to an array variable in order to append new elements to the array. It also must be noted that, in an arithmetic context, the expression on the right side of the += operator is evaluated as an arithmetic expression and added to the variable’s current value.

like image 163
M. Nejat Aydin Avatar answered Oct 31 '25 07:10

M. Nejat Aydin