【问题标题】:Gunzip from stringGunzip 从字符串
【发布时间】:2017-10-14 19:22:32
【问题描述】:

我有一个问题。我想直接从文件中解压缩字符串。我在 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 has flags 0x81 -- not supported 你知道我为什么会遇到这个问题吗?

【问题讨论】:

    标签: linux bash escaping gzip gunzip


    【解决方案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
    

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

    最好的折衷办法可能是使用 base64 编码:

    gzip <<<"My name is Daniel"| base64
    
    base64 --decode <<__END__ | gzip -cd
    H4sIAPts4lkAA/OtVMhLzE1VyCxWcEnMy0zN4QIAgdbGlBIAAAA=
    __END__ 
    

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

    【讨论】:

      【解决方案2】:

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

      我想避免使用 base64,但我用

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

      我用 bless hex 编辑器编辑了脚本。它对我有用:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多