PanD22
PanD22

Reputation: 91

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?

Upvotes: 4

Views: 3614

Answers (1)

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10103

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.

Upvotes: 7

Related Questions