DKR Computing

                                                            

  • Increase font size
  • Default font size
  • Decrease font size
Home DKR Computing Articles Linux Generate Random Hex Digits Using the Unix Shell

Generate Random Hex Digits Using the Unix Shell

E-mail Print PDF

Here is a script that will randomly generate a hexadecimal digit. Please enjoy!

# randomhexdigit.sh - Version 0.01
#
# A simple Unix shell script that generates a random hexadecimal digit.
#
# Written by: Keith Rice
#
# This script is free to use but please credit me and/or link to my site.
# http://dkrcomputing.com
# You are free to modify this script to your heart's delight, but PLEASE
# DO NOT DISTRIBUTE MODIFIED VERSIONS! Please send comments and recommendationss
# for improvement to This e-mail address is being protected from spambots. You need JavaScript enabled to view it .

# Step 1: Get a random number using the $RANDOM environment variable
NUM=${RANDOM}

# Step 2: Perform modulo arithmetic using the 'let' shell command. Perform
#         MOD 15 on the random number to get a number from 0 to 15.
let "NUM %= 15"

# Step 3: Convert our decimal number from step 2 into a hexadecimal digit
#         by using the bc utility.
echo "obase=16;$NUM" | bc

# end of randomhexdigit.sh

Last Updated on Thursday, 13 October 2011 15:19  

Follow us on Twitter