I recently spent some time trying to write some numbers as bytes to pipe using bash (e.g. 10 as 0xA
, not 0x310x30
). Unfortunately I was not able to do so and had to rewrite the script into Python. Is it any way to send data as bytes in bash script and not as characters?
Asked
Active
Viewed 2,295 times
3

Adam Sznajder
- 9,108
- 4
- 39
- 60
-
1You might be interested in my pure-Bash implementation of `hexdump` found in [this SO answer](http://stackoverflow.com/a/2004276/26428) and distributed as an example script with Bash 4.2. – Dennis Williamson Jun 21 '12 at 00:39
-
related: [How to convert an unsigned decimal (less than 1<<32) to 4 bytes (binary) in bash?](http://unix.stackexchange.com/q/157648/1321) – jfs Sep 26 '14 at 06:55
2 Answers
2
You can specify arbitrary characters in bash
using $'...'
syntax. $'\012'
$'\x0a'
would be the byte with decimal value 10 in octal and hex, respectively. See the bash
man page under QUOTING.

chepner
- 497,756
- 71
- 530
- 681
-
What if I want to send something that I have e.g. in `testVar` variable? I tried to use `$'...'` syntax but without success. – Adam Sznajder Jun 20 '12 at 21:20
-
1Then it's up to the reader of the variable to treat the value as a sequence of bytes, rather than a sequence of printable characters. You don't have to do anything special. – chepner Jun 20 '12 at 22:14
2
As chepner told, you can output any value as e.g.: $'\012'. So, a short script:
convert() {
printf \\$(printf '%03o' $1)
}
convert 122 | od -bc
The right print will convert the decimal argument into octal number and the second print will print the octal number as above... e.g. decimal 65 will be converted into byte 'A'.

clt60
- 62,119
- 17
- 107
- 194