Bash: checking gzip using == or "| grep"

53 views Asked by At

I have a simple question here. I have a file and want to check if it is gzipped or not. I've had cases where people rename files without .gz so I'm using file $name instead of looking for ".gz" in the filename. The output of file $filname gives a long string: zip1.gz: gzip compressed data, was "zip1", from Unix, last modified: Fri Jan 26 11:01:59 2024.

I have two commands that appear to both work.

if file $filename | grep -q gzip ; then

if [[ $(file $filename) == *"gzip"* ]] ; then

Which way is preferred?

I also don't know why the first method works. file $filename outputs a string, correct? Then that string is piped to the input of grep. I thought grep accepts a file as an input, not a string.

2

There are 2 answers

1
Gilles Quénot On

What I would do:

if file -i "$file" | grep -q 'application/gzip'; then
    [...]
else
    echo >&2 "$file is not a gzip file"
fi

or

mytype=$(file -i "$file")
case "$mytype" in
    *application/gzip*)
        [...]
    ;;
    *)
        echo >&2 "$file is not a gzip file"
    ;;
esac

Both solutions don't need , you even can use sh with them.

0
Antonio Petricca On

Try with:

if gunzip --test "${file}" 2>/dev/null 1>/dev/null; then
  echo "This is a gzipped file!"
else
  echo "This is NOT a gzipped file."
fi