theGrayFox
theGrayFox

Reputation: 931

List of characters and digits

What's the best way of defining a list of characters that consist of the following: a-z, A-Z, and 0-9? I really wanted to avoid typing one huge array to hold this data, how can I accomplishing this in Bash? In Python, this list of data can be joined as such:

for i in xrange(length):
    password += random.choice(string.ascii_letters + string.digits)

print password

Upvotes: 1

Views: 123

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 125838

I don't think you really need an array for this, just a string (since it's easy to pick the n'th character out of a string):

printf -v chars "%s" {a..z} {A..Z} {0..9}
nchars=${#chars}
for ((i=1; i<=length; i++)); do
    password+="${chars:RANDOM%nchars:1}"
done

Upvotes: 5

Kent
Kent

Reputation: 195079

if the list you meant is a string, you could:

Bash

kent$ echo {a..z} {A..Z} {0..9}
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9

zsh

kent$  echo {a-z} {A-Z} {0-9}

I hope this is what you are looking for.

EDIT

OP wants an array:

kent$ arr=( {a..z} {A..Z} {0..9} )
kent$ echo ${arr[@]}
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9
kent$ echo ${arr[3]}
d

Upvotes: 4

dinox0r
dinox0r

Reputation: 16039

Generate an array this way:

array=( ); 
i=0; 
for c in {a..z} {A..Z} {0..9}; do 
    array+=("$c"); 
    let i++; 
done

Upvotes: 1

Related Questions