Search code examples
linuxbashcompressiongzip

(Un/De)compress a string in bash?


Is it possible to compress/decompress a string in bash using stdin/stdout ?

I tried this but apparently it is not supported ?

hey=$(echo "hello world" | gzip -cf)
echo $hey # returns a compressed string
echo $hey | gzip -cfd
gzip: stdin is a multi-part gzip file -- not supported

I'm not well versed in linux but I read other compression utilities man pages and couldn't find a solution?


Solution

  • When you do:

    hey=$(echo "hello world" | gzip -cf)
    

    You don't have same same bytes in variable hey as you have in /tmp/myfile created by:

    echo "hello world" | gzip -cf > /tmp/myfile
    

    You get "gzip: stdin is a multi-part gzip file -- not supported" error simply because you have broken compressed data which cannot be uncompressed.

    The VAR=$(...) construction is designed for working with text. This is why you get extra trailing trim for example.