Reputation: 689
I've found many posts on StackOverflow which have covered this question in C++, C# and other languages, but none with Shell.
Using Bash/Shell, how do I convert a random String
into a byte array
?
I tried:
echo "some string" | xxd -r -p
but it didn't work.
I basically want a byte output - e.g. )?e?GV??vY?Ge?#G
Upvotes: 17
Views: 30000
Reputation:
If you want to get the hex values of some string, then this works:
$ echo "testing some values"$'\157' | xxd
0000000: 7465 7374 696e 6720 736f 6d65 2076 616c testing some val
0000010: 7565 736f 0a ueso.
If you just need the "plain" string:
$ echo "testing some values"$'\157' | xxd -p
74657374696e6720736f6d652076616c7565736f0a
If you need to "reverse" an hex string, you do:
$ echo "74657374696e6720736f6d652076616c7565736f0a" | xxd -r -p
testing some valueso
If what you need is the character representation (not hex), you could do:
$ echo "testing:"$'\001\011\n\bend test' | od -vAn -tcx1
t e s t i n g : 001 \t \n \b e n d
74 65 73 74 69 6e 67 3a 01 09 0a 08 65 6e 64 20
t e s t \n
74 65 73 74 0a
Or:
$ echo "testing:"$'\001\011\n\bend test' | od -vAn -tax1
t e s t i n g : soh ht nl bs e n d sp
74 65 73 74 69 6e 67 3a 01 09 0a 08 65 6e 64 20
t e s t nl
74 65 73 74 0a
Upvotes: 33
Reputation: 7258
Looks like you want to convert hex string to bytes. xxd needs a starting point (since it is used to patch binary files and such)
string="626c610a"
echo "0: $string" | xxd -r
xxd will also silently skip any invalid hex, so check your data if you get empty output.
Upvotes: 0