0

The following script checks whether FILE is in the directory.

The FILE includes 'name.pdf'

How to verify, that files name*.pdf are also in the directory?

if [ -f "$FILE" ]; then  # ----> how to add the condition that name*.pdf is also OK
    echo "OK $f"
else 
    echo "!!! Not OK $f"
fi
Elena Greg
  • 1,061
  • 1
  • 11
  • 26
  • could you provide a sample listing of your target directory? _"..files name*.pdf are **also** in the.."_ your question seems a little unclear. – kevinnls Apr 11 '21 at 08:43
  • 1
    This looks like a duplicate of ["Test whether a glob has any matches in bash"](https://stackoverflow.com/questions/2937407/test-whether-a-glob-has-any-matches-in-bash) -- do the answers to that question cover what you need? – Gordon Davisson Apr 11 '21 at 09:03

3 Answers3

1

You can do this:

if [ -f name*.pdf ]; then
    echo "OK $f"
else 
    echo "!!! Not OK $f"
fi

EDIT: as stated in the comments this method won't work if more than one file match, so I've found another way:

name=name*.pdf;
if compgen -G $name > /dev/null; then
    echo "OK $f"
else 
    echo "!!! Not OK $f"
fi
Leo Lamas
  • 178
  • 9
1

Does this do what you want?

 # List the files, but stream any output to /dev/null
 # We are only interested in the exit status                   
if ls name*.pdf >/dev/null 2>&1; then 
    echo File matching pattern exist
else
    echo Files matching pattern do not exist
fi

This works because if is checking the exit status of the ls command. This is exactly how if [ 'some condition' ] works, which is a shortcut for if test 'some condition': if is checking the exit status of test. ls has an exit status of 0 if it finds files, otherwise it's 1 or 2 both of which if will evaluate as false.

If you want a more general solution, you can define the prefix and extension as variables:

prefix='name' #You can define the prefix and extension as variables
ext='pdf'

if $prefix*.$ext >/dev/null 2>&1; then
#the rest of the code is the same as earlier.
Mehmet Karatay
  • 269
  • 4
  • 11
-1

You could follow something like below

#!/bin/bash

if [[ $(find . -name "name-*.pdf") ]]; then
        echo "File Exists"
else
        echo "File Doesnt exists"
fi
Nishant Jain
  • 197
  • 1
  • 9
  • 2
    Keep out: the `find` command automatically searches subdirectories as well. In order to avoid (or to limit) that, you might need the `-maxdepth` parameter. – Dominique Apr 11 '21 at 08:48
  • 2
    Also, `name-*.pdf` needs to be quoted so the shell doesn't expand it before passing it to `find`. And you should use `find .` because some versions of `find` expect you to explicitly tell them what directory to search (I think only GNU `find` allows you to omit it). – Gordon Davisson Apr 11 '21 at 08:57
  • Thanks Gordon and Dominique for your comments. I will fix it. – Nishant Jain Apr 13 '21 at 08:51