Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating random string zsh

Tags:

random

zsh

I am trying to generate a random string with the following code:

for pic in `ls *.jpg`; do
  rdn=`echo $RANDOM | sha256sum | cut -d" " -f1`
  mv "$pic" ${rnd}.jpg
done

This part of the script runs from within a directory containing lots of jpeg files and it should randomize their filenames. The problem is that the $RANDOM variable does not update during the iteration, and therefore gives the same hash every time. I tried to use /dev/urandom, and it works, but is a lot slower than $RANDOM. What can I do to "regenerate" $RANDOM every time it is read?

like image 349
wafel Avatar asked Dec 15 '22 04:12

wafel


1 Answers

On my mac (using macOS High Sierra), the /dev/urandom gives me binary bytes, so the above solution results in tr: Illegal byte sequence, so I used base64 to convert bytes to characters:

cat /dev/urandom | base64 | tr -dc '0-9a-zA-Z' | head -c100

or I found a solution without base64 so you can get punctuation as well:

cat /dev/urandom | LC_ALL=C tr -dc '\''[:alnum:]\!\@\#$\-\.\,'\'' | head -c40
like image 92
Ivan Marinov Avatar answered Jan 05 '23 16:01

Ivan Marinov