Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Created October 24, 2012 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zonuexe/3948633 to your computer and use it in GitHub Desktop.
Save zonuexe/3948633 to your computer and use it in GitHub Desktop.
rand in SHELL

rand in SHELL

inspired by rubyとzshを使ってランダム文字列を生成する - Qiita and kyanny/securerandom-cli · GitHub

requirement

  • Bourne shell like shells ( sh, bash, zsh )
  • Ruby version 1.9+

How to use

rand          ; => 85800d9d5b (default 10 charactors)
rand 10       ; => f5794c8d18373d6 (your ordered string length)
rand hex 10   ; => d849dc6de1953eab647a (your ordered algorithm)
rand uuid     ; => e5c9aaf9-2484-47ad-a419-61860cb1157a (UUID)
rand u        ; => 663704fb-d0ce-446a-8320-68c9c009c078 (be able abbreviated, means uuid)
rand n 100000 ; => 73889 (put a integer number, range 1 <= n < arg)
rand f        ; => 0.822746453691208 (put a floating-point number, range 0 <= n < 1)
rand () {
a=$1
b=$2
type=random_string
len=10
post="cat -"
chop="sed -e s/.$//g"
case `echo $a | tr '[:upper:]' '[:lower:]'` in
"") a=$type; b=$len ;;
ba*) a=base64 ;;
f*) a=random_float ;;
h*) a=hex ;;
b*) a=random_bytes ;;
u*) a=uuid ;;
s*) a=random_string ;;
n*) a=random_number ;;
esac
if test "$a" = uuid
then type=uuid; len=''
elif test "$a" = random_float
then type=random_number; len=0
elif test "$a" = random_string -o "$b" = ""
then
type=hex
test ! "$b" && l=$a
if test "$b" -gt 0 2>/dev/null
then l=$b
fi
len=`expr $l / 2`
mod=`expr $l % 2`
if test "$l" = 1
then post="$chop"; len=1
elif test $mod = 1
then post="$chop"; len=`expr $len + 1`
fi
elif test "$a" -a "$b"
then type=$a; len=$b
elif test "$a"
then len=$a
fi
ruby -rsecurerandom -e "puts SecureRandom.${type} ${len}" | eval $post
}
@zonuexe
Copy link
Author

zonuexe commented Oct 25, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment