1

I need to check if a file with a specific extension exists and if it is not empty. The problem is that I don't know the name of the file, just the extension and the path.

Here my solution with an known name

FILE="/Users/test/my.out"
if [[ -f $FILE  &&  -s $FILE ]] ; then echo "EXIST"; fi

Using

FILE="/Users/test/*.out"

Do not work

2
  • What if you have multiple files that match that pattern? Try FILE=$(ls /Users/test/*.out) Commented Apr 4, 2014 at 9:10
  • The initial condition is that in this folder will be just one file .out Commented Apr 4, 2014 at 9:19

4 Answers 4

4

I suggest you use an array, in case there are multiple files:

arr=( /Users/test/*.out )

if (( ${#arr[@]} > 0 )) && [[ -s "${arr[0]}" ]]
then
    ...
fi
Sign up to request clarification or add additional context in comments.

Comments

1

You can either use @dogbane's solution using an array or use a loop:

dir=/users/test
for file in "${dir}"/*.out; do
    break
done

if [ -f "${file}" ] && [ -s "${file}" ]; then
    echo "found a regular, non-empty .out file: ${file}"
fi

Comments

-1

I think this should do:

if [ -f ${var} ]; then
   if [ -s ${var} ]; then
      echo  "Found $var"
   fi
fi

Comments

-2

Try

FILE=$(ls "Downloads/*.zip" 2>/dev/null)

Only works, if there is only a single file.

3 Comments

This works, thanks! If I put in a while loop this check, if the file does not exist yet, an output "ls: /Users/test/*.out: No such file or directory" is displayed. Is there any way to avoid this output?
See my edit, the 2>/dev/null suppresses the error. By the way, I guess this is a very bad hackjob...
Thanks everyone for downvoting and telling the world your reasons. Some arguments against it can be found here..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.