Gunzip来自弦乐队

时间:2017-10-14 19:22:33

标签: linux bash escaping gzip gunzip

我有一个问题。我想直接从文件中解压缩字符串。我在bash中有一个脚本可以创建另一个脚本。

#!/bin/bash


echo -n '#!/bin/bash 
' > test.sh #generate header for interpreter
echo -n "echo '" >> test.sh #print echo to file
echo -n "My name is Daniel" | gzip -f >> test.sh #print encoded by gzip string into a file
echo -n "' | gunzip;" >> test.sh #print reverse commands for decode into a file
chmod a+x test.sh #make file executable

我想生成最短脚本的脚本test.sh。我试图压缩字符串"我的名字是丹尼尔"并将其直接写入文件test.sh

但是如果我运行test.sh我得到了gzip:stdin有标志0x81 - 不支持 你知道我为什么会遇到这个问题吗?

2 个答案:

答案 0 :(得分:2)

gzip输出是二进制的,所以它可以包含任何字符,因为脚本是用bash生成的,它包含编码的字符(echo $LANG)。

导致单引号出现问题的

字符为NUL 0x0' 0x27和非ascii字符128-256 0x80-0xff

解决方案可以是使用ANSI C引号$'..'并转义NUL和非ascii字符。

编辑bash字符串不能包含空字符:

gzip -c <<<"My name is Daniel" | od -c -tx1 

尝试创建ansi字符串

echo -n $'\x1f\x8b\x08\x00\xf7i\xe2Y\x00\x03\xf3\xadT\xc8K\xccMU\xc8,VpI\xcc\xcbL\xcd\^C1\x00\xa5u\x87\xad\x11\x00\x00\x00' | od -c -tx1

表示字符串在空字符后被截断。

最好的折衷方案可能是使用base64编码:

gzip <<<"My name is Daniel"| base64

base64 --decode <<__END__ | gzip -cd
H4sIAPts4lkAA/OtVMhLzE1VyCxWcEnMy0zN4QIAgdbGlBIAAAA=
__END__ 

base64 --decode <<<H4sIAPts4lkAA/OtVMhLzE1VyCxWcEnMy0zN4QIAgdbGlBIAAAA=|gzip -cd

答案 1 :(得分:0)

问题在于在bash脚本中存储空字符(\ 0)。 空字符不能存储在echo和变量字符串中。它可以存储在文件和管道中。

我想避免使用base64,但我用

修复了它
printf "...%b....%b" "\0" "\0"

我用bless hex编辑器编辑了脚本。它为我工作:))