2017-10-14 159 views
0

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

#!/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 - 不支持 你知道为什么我有这个问题吗?

回答

1

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 
0

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

我想避免使用的base64,但我

printf "...%b....%b" "\0" "\0" 

固定它,我编辑与祝福十六进制编辑器脚本。它为我工作:)

相关问题