将二进制文件读入bash中的变量 [英] Reading a binary file into variable in bash

查看:62
本文介绍了将二进制文件读入bash中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下bash脚本.我希望文件out.1和out.2是相同的,但是它们是不同的.我怀疑问题是bash如何处理二进制文件.那么将二进制文件读入bash中的变量的正确方法是什么?

I have the following bash script. I expect the files out.1 and out.2 to be the same, but they are different. I suspect that the problem is how bash deals with binary files. So what is the proper way to read in a binary file into a variable in bash?

curl -s http://cacerts.digicert.com/DigiCertSHA2HighAssuranceServerCA.crt > out.1
A=`curl -s http://cacerts.digicert.com/DigiCertSHA2HighAssuranceServerCA.crt`
echo "$A" >  out.2
diff out.1 out.2

推荐答案

bash变量(以及环境变量,unix参数和...)不是二进制安全的.最大的问题是它们不能包含零字节(即ASCII NUL字符),因为这是一个字符串终止符.在某些情况下,最后还会删除/添加换行符,这也存在一些问题,并且某些版本的 echo 将反斜杠字符视为需要解释的转义字符.基本上,答案是:不要尝试在shell中存储二进制数据.

bash variables (and environment variables, and unix arguments, and...) are not binary-safe. The biggest problem is that they cannot contain zero bytes (i.e. the ASCII NUL character), since that's a string terminator. There are also problems with newlines being removed/added at the end in some situations, and some versions of echo treat backslash characters as escapes that it needs to interpret. Basically, the answer is: don't try to store binary data in the shell.

但是您可以将数据转换为非二进制格式(十六进制,base64,uuencode等),并以该格式存储,传递等数据.只要确保在适当的地方转换格式即可.这是使用base64的示例:

But you can convert the data to a non-binary format (hex, base64, uuencode, whatever), and store, pass, etc data in that form. Just be sure to convert formats wherever appropriate. Here's an example of using base64:

$ curl -s http://cacerts.digicert.com/DigiCertSHA2HighAssuranceServerCA.crt > out.1
$ a=$(curl -s http://cacerts.digicert.com/DigiCertSHA2HighAssuranceServerCA.crt | base64)
$ echo "$a" | base64 -d >out.2
$ diff -s out.*
Files out.1 and out.2 are identical

顺便说一句,我建议使用小写或混合大小写的变量名(有一堆具有特殊含义的全大写变量,并且偶然使用其中一个变量可能会产生奇怪的效果),还建议使用 $()而不是反引号(易于阅读,并且避免了一些晦涩的语法怪异).

BTW, I recommend using lower- or mixed-case variable names (there are a bunch of all-caps variables with special meanings, and using one of those by accident can have weird effects), and also using $( ) instead of backticks (easier to read, and avoids some obscure syntactic oddities).

这篇关于将二进制文件读入bash中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆