我有一个问题。我想直接从文件中解压字符串。我在 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。我正在尝试压缩字符串“My name is Daniel”并将其直接写入文件 test.sh
但是如果我运行 test.sh 我得到 gzip: stdin has flags 0x81 -- not supported 你知道我为什么会遇到这个问题吗?
最佳答案
gzip 输出是二进制的,所以它可以包含任何字符,因为脚本是用 bash 生成的,它包含编码的字符 (echo $LANG
)。
导致单引号之间出现问题的字符是 NUL 0x0
、' 0x27
和非 ascii 字符 128-256 0x80-0xff
。
一个解决方案是使用 ANSI C 引号 $'..'
并转义 NUL 和非 ascii 字符。
编辑 bash 字符串不能包含 nul 字符:
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
显示字符串在 nul 字符后被截断。
最好的折衷方案可能是使用 base64 编码:
gzip <<<"My name is Daniel"| base64
base64 --decode <<__END__ | gzip -cd
H4sIAPts4lkAA/OtVMhLzE1VyCxWcEnMy0zN4QIAgdbGlBIAAAA=
__END__
或
base64 --decode <<<H4sIAPts4lkAA/OtVMhLzE1VyCxWcEnMy0zN4QIAgdbGlBIAAAA=|gzip -cd
关于linux - 从字符串中压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46748460/