July 14th, 2003, 01:15 AM
I am trying to write a shell script. Does anyone know how to check in a shell script to see if a file is a gzip. For example, I want to write something similar to this pseudocode
if( $1 is gz)
then do something
do something esle
Also, does anyone know how to tell the last time a file was edited meaning how old the file is?
July 14th, 2003, 01:22 PM
echo $1 | grep 'gz$' > /dev/null
if [ $? -eq 0 ]
ls -l <filename> will show the date of the last edit
December 23rd, 2003, 08:02 AM
two other ways where you do not rely on file extension:
1/ gzipped files always start with the same 2 bytes which are: "8b1f" hexadecimal. So let have a look at it:
hexdump some_gzip_file.gz | head -n 1 | cut -f2 -d' '
hexdump does what it says. we take the first line of the output and then the second column which is the first 2 bytes of the file. We can store the value in a variable and then make some tests.
GZIP_WORDS=`hexdump some_gzip_file.gz | head -n 1 | cut -f2 -d' '`
test "$GZIP_WORDS" = "8b1f" && echo "gzip here"
2/ Why bother when we have nifty tools doing the job for us:
file -b -n some_gzip_file.gz gzip compressed data, deflated, last modified: Thu Jan 1 01:00:00 1970, os: Unix
Cutting for the first word will give the answer you need:
file -b -n smtp-vilter-1.0.5.tar.gz |cut -f 1 -d' '
man file for more information.