Skip to content

Instantly share code, notes, and snippets.

@lmlsna
Created February 1, 2018 01:35
Show Gist options
  • Save lmlsna/03cb01e98028fce45b9b0e2f4f14bb95 to your computer and use it in GitHub Desktop.
Save lmlsna/03cb01e98028fce45b9b0e2f4f14bb95 to your computer and use it in GitHub Desktop.
Convert string to int in bash.
#!/bin/bash
# This is a simple bash function to change strings (of arbitrary length) into integers (of arbitrary maximums).
# I use this to convert my "user@hostname" to a number between 1-255 and use that as a persistent color for the
# termnal prompt to remind me what box/user I am on.
#
# It just hashes whatever string you give it, converts the hex to a decimal and then mods around whatever your max int is.
# Usage: str_to_int [string_to_convert] [max_int_size]
# Example: str_to_int "user@hostname" 255
#
function str_to_int {
echo $(( 0x$(echo -n "$1" | sha1sum | cut -d " " -f 1) % $2 ))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment