28

I need to pass binary data to a bash program that accepts command line arguments. Is there a way to do this?

It's a program that accepts one argument:

script arg1

But instead of the string arg1, I'd like to pass some bytes that aren't good ASCII characters - in particular, the bytes 0x02, 0xc5 and 0xd8.

How do I do this?

phs
  • 10,687
  • 4
  • 58
  • 84
Cam
  • 14,930
  • 16
  • 77
  • 128

5 Answers5

27
script "`printf "\x02\xc5\xd8"`"
script "`echo -e "\x02\xc5\xd8"`"

test:

# echo -n "`echo -e "\x02\xc5\xd8"`" | hexdump -C
00000000  02 c5 d8                                          |...|
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
27

Use the $'' quote style:

script $'\x02\xc5\xd8'

Test:

printf $'\x02\xc5\xd8' | hexdump -C
00000000  02 c5 d8
l0b0
  • 55,365
  • 30
  • 138
  • 223
  • `$''` is Bash mechanism for quoting [ANSI C like strings](http://wiki.bash-hackers.org/syntax/quoting#ansi_c_like_strings) – UrsaDK Dec 24 '18 at 15:46
7

Bash is not good at dealing with binary data. I would recommend using base64 to encode it, and then decode it inside of the script.

Edited to provide an example:

script "$(printf '\x02\xc5\xd8' | base64 -)"

Inside of the script:

var=$(base64 -d -i <<<"$1")
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • 2
    Agreed. I haven't found any way to get bash to deal with zero bytes (\x00) in strings, and it tends to add/remove trailing newlines (\x0a) as it thinks best -- both are quite bad when dealing with arbitrary binary data. – Gordon Davisson Feb 28 '12 at 18:14
0

How about this?

$ script "`printf "\x02\xc5\xd8"`"
Bartosz Moczulski
  • 1,209
  • 9
  • 18
-2

Save your binary data to a file, then do:

script "`cat file`"
Eduardo Ivanec
  • 11,668
  • 2
  • 39
  • 42