0

How to convert text to hexadecimal in bash script?

Example:

#!/bin/bash
myvar="abc '\\ special chars, etc..."

# need $myvar in hexadecimal: 616263...

I tried:

myvar=`printf $plaintext | xxd --p`

But does not works, $plaintext contain special chars by example

$plaintext='demo && evil command injected'

How to convert var into hex value safely? or can save buffer to variable like this?:

printf $abc | xxd --p | def=
e-info128
  • 3,727
  • 10
  • 40
  • 57

1 Answers1

1

I haven't used xxd before. It seems that xxd -p will always group the plain output into columns, and you can't turn that off. Instead, you can use hexdump for this. It tends to be available on many Linux platforms. Example:

myvar=$(hexdump -ve '1/1 "%02x"' <<< 'Hello, World!')
echo $myvar

Results in:

48656c6c6f2c20576f726c64210a
paddy
  • 60,864
  • 6
  • 61
  • 103