Skip to content

Instantly share code, notes, and snippets.

@nberlette
Last active February 26, 2024 08:01
Show Gist options
  • Save nberlette/e3e303a81f2c41927bf4fe90fb89d97f to your computer and use it in GitHub Desktop.
Save nberlette/e3e303a81f2c41927bf4fe90fb89d97f to your computer and use it in GitHub Desktop.
[bash] rgb to hex

hex.sh

This is a tiny (140B) bash script to convert rgb (0-255,0-255,0-255) into hexadecimal (000000-FFFFFF).

#!/bin/bash
function hex() {
    printf "%02X%02X%02X" ${*//','/' '}
}
[ $(basename -- $0) == "hex" ] && [ $# -gt 0 ] && echo $(hex "${*}")

Usage

It can interpret a few different input styles:

hex 255 255 255   # FFFFFF
hex 255,255,255   # FF0000
hex "128 200 250" # 80C8FA

Install

Just drop hex.sh in your $PATH, after you make sure it's executable:

sudo chmod +x hex.sh

# my preference is $HOME/.local/bin
mv hex.sh /usr/local/bin/hex

You can also opt to source the code into another script, to call hex programmatically:

[ -f ./hex.sh ] && . ./hex.sh

echo $(hex 255 0 0)   #FF0000

I've tested all this on macOS (darwin) and Debian/Ubuntu, without any issues.
This also works on iOS via iSH (Alpine Linux). Windows... not so much.

License

MIT © 2021 Nicholas Berlette

#!/bin/bash
function hex() {
printf "%02X%02X%02X" ${*//','/' '}
}
[ $(basename -- $0) == "hex" ] && [ $# -gt 0 ] && echo $(hex "${*}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment