0

In bash I can call PHP and run the following:

testKey='8798(*&98}9%"^8&]8_98{9798**76876'
testHex=$(php -r "echo bin2hex('$testKey');")
echo $testHex

And that will result in 38373938282a2639387d3925225e38265d385f39387b393739382a2a3736383736

I've got a system where PHP isn't available, is there anyway to get the same result using just bash ?

Thanks

user214292
  • 183
  • 1
  • 1
  • 4

3 Answers3

4

If you have hexdump lying around:

$ printf "%s" "$testKey" | hexdump -ve '/1 "%x"'
38373938282a2639387d3925225e38265d385f39387b393739382a2a3736383736

-e sets a format string for hexdump, which 'must be surrounded by double quote ( " ) marks'. /1 uses one byte at a time for the format string %x, which prints it in hex (otherwise the byte order could result in different output). -v is to make it print repeated data as well (the default is to replace them with a *).

muru
  • 69,900
  • 13
  • 192
  • 292
2

Yes, with xxd you can do exactly the same:

testKey='8798(*&98}9%"^8&]8_98{9798**76876'
testHex=$(echo -n "${testKey}" | xxd -p -c 100)

The -p flag is for a hex dump without offset information.
The -c 100 flag is for a line-length of 100 characters(default is 16, max 256).

noAnton
  • 361
  • 1
  • 6
0

With "just bash", using a trick from BASH print question (printf \$(printf '%03o' $1))

$ for ((i=0;i<${#testKey};i++)); do printf '%x' "$(printf "'%c" "${testKey:i:1}")"; done; echo
38373938282a2639387d3925225e38265d385f39387b393739382a2a3736383736

With perl's unpack

$ perl -E 'say unpack "H*", $ARGV[0]' "$testKey"
38373938282a2639387d3925225e38265d385f39387b393739382a2a3736383736
steeldriver
  • 78,509
  • 12
  • 109
  • 152