Checking if file exists and unzipping

Hey, I am new to scripting and was wondering what is wrong with this if statement. I want to check if file exists and the if it does to unzip it. I program it as follows

if [ -e *_filename.gz ]; then
gunzip *_filename.gz 
fi

Thanks in advance!

Try -f instead:-

if [ -f *_filename.gz ]; then

The -f option does not work either! :frowning:

Works for me:-

# ls -l
-rwxr-xr-x   1 user    group         157 Nov 19 09:10 test1.gz
-rw-r--r--   1 user    group          39 Nov 19 10:39 test2.gz

# if [ -f *test*.gz ]
> then
>    echo Yes
> else
>    echo No
> fi
Yes
# rm -f *.gz
# if [ -f *test*.gz ]
> then
>    echo Yes
> else
>    echo No
> fi
No

What is your OS / Platform?

This will fail in many systems because -f will get confused when given more than one argument.

I'd use a for-loop instead, breaking so it only runs once. Or not, if you want to run it over all files...

for FILE in *.gz
do
        if ! [ -f "$FILE" ] 
        then
                echo "No gz files"
       fi
       echo "$FILE exists"
       break
done
1 Like

Or you can use ls to check:-

if [ $( ls -l *_filename.gz 2> /dev/null | wc -l ) -ne 0 ]
then
      gunzip *_filename.gz
fi

That is a useless use of ls *, running ls here is redundant. It will also cause error message spam when no files are present.

Corona688, I am redirecting error to /dev/null , BTW why ls is redundant here?

Because you're running an external program when there was no need to do so.

Actually, you're running two external programs when there was no need to do so, inside a subshell, so a waste of three processes as opposed to zero.

Got it, so actually it is not redundant but not required or inefficient. As per the page I think it is said redundant because ls is used in a for loop with *glob.

It's redundant because you don't actually need the ls to list the files. If you're globbing, you already have them.