27

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,378
  • 3
  • 56
  • 80
Cam
  • 14,575
  • 16
  • 74
  • 124

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
  • 91,854
  • 11
  • 113
  • 173
26

Use the $'' quote style:

script $'\x02\xc5\xd8'

Test:

printf $'\x02\xc5\xd8' | hexdump -C
00000000  02 c5 d8
l0b0
  • 52,149
  • 24
  • 132
  • 195
  • `$''` 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
6

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
  • 29,762
  • 6
  • 59
  • 72
  • 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,178
  • 8
  • 18
-1

Save your binary data to a file, then do:

script "`cat file`"
Eduardo Ivanec
  • 11,314
  • 2
  • 37
  • 42