bash 在bash中将二进制数据作为参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9487037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:43:08  来源:igfitidea点击:

Passing binary data as arguments in bash

bashcharacter-encodingparameters

提问by Cam

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

我需要将二进制数据传递给接受命令行参数的 bash 程序。有没有办法做到这一点?

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, 0xc5and 0xd8.

但是,而不是字符串arg1,我想通过一些字节是不好的ASCII字符-特别是字节0x020xc50xd8

How do I do this?

我该怎么做呢?

采纳答案by Karoly Horvath

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                                          |...|

回答by l0b0

Use the $''quote style:

使用$''引用样式:

script $'\x02\xc5\xd8'

Test:

测试:

printf $'\x02\xc5\xd8' | hexdump -C
00000000  02 c5 d8

回答by jordanm

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.

Bash 不擅长处理二进制数据。我建议使用 base64 对其进行编码,然后在脚本内部对其进行解码。

Edited to provide an example:

编辑以提供示例:

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

Inside of the script:

脚本内部:

var=$(base64 -d -i <<<"")

回答by Bartosz Moczulski

How about this?

这个怎么样?

$ script "`printf "\x02\xc5\xd8"`"

回答by Eduardo Ivanec

Save your binary data to a file, then do:

将二进制数据保存到文件中,然后执行以下操作:

script "`cat file`"