I need to create a random String to save in a variable.
var=`??????`
So I want to replace ?????? with random 8 chars for instance:
is96789h
only letters and numbers
Is there an easy way to do this?
Thanks as always
DV
I need to create a random String to save in a variable.
var=`??????`
So I want to replace ?????? with random 8 chars for instance:
is96789h
only letters and numbers
Is there an easy way to do this?
Thanks as always
DV
var=`perl -MList::Util=shuffle -le '@s = shuffle (a..z, 0..9); print @s[0..7]'`
Hi.
Here are two more solutions, both using different perl modules.
Observations: the shuffle would not return any duplicates, the Data/Random would not return duplicates until the result is quite long -- longer than the source strings (this is partly a guess and partly observation), the Data/Random/String can return duplicates as seen below.
The choice depends on the application.
#!/usr/bin/env bash
# @(#) s1 Demonstrate perl modules for string of random characters.
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C perl
var=`perl -MList::Util=shuffle -le '@s = shuffle (a..z, 0..9); print @s[0..7]'`
pl "Random list as string (shuffle): $var"
var=$(perl -e 'use Data::Random qw(:all);print join("",rand_chars(set => 'alphanumeric', size => 8)),"\n";' )
pl " Random list as string (Random): $var"
var=$(perl -e 'use Data::Random::String; print Data::Random::String->create_random_string(length=>8, contains=>"alphanumeric"),"\n";')
pl " Random string (String): $var"
exit 0
producing:
% ./s1
Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution : Debian GNU/Linux 5.0.8 (lenny)
bash GNU bash 3.2.39
perl 5.10.0
-----
Random list as string (shuffle): g2lto9kn
-----
Random list as string (Random): s6S5A8tD
-----
Random string (String): 6E6wfo0C
Best wishes ... cheers, drl
#!/bin/bash
ary=({a..z} {A..Z} {0..9})
for i in {0..7}; do
echo -n ${ary[RANDOM%${#ary[@]}]}
done
echo