Search code examples
bashhexascii

bash ascii to hex


was wondering if anyone could help me with converting ascii to hex in bash. Example code:

#!/bin/bash 
STR = "hello"
#Convert to hex
HEXVAL = $STR #(in hex here?)

I want hexval to have the value: 68656C6C6F (hello in hex)


Solution

  • $ str="hello"
    $ hex="$(printf '%s' "$str" | xxd -p -u)"
    $ echo "$hex"
    68656C6C6F
    

    Or:

    $ hex="$(printf '%s' "$str" | hexdump -ve '/1 "%02X"')"
    $ echo "$hex"
    68656C6C6F
    

    Careful with the '"%X"'; it has both single quotes and double quotes.