0

I want to check if file exists but only checking if some the filename exists

For example in some folder I have these files (Date format: AAAAMMDD):

Rejets_20190112.csv.zip

Rejets_20190312.csv.zip

Rejets_20190314.csv.zip

I want to check if there is a file that begins with Rejet_DAP_201903 exists in that folder. In other word I want to check if Rejet_DAP file with current year and month exist, the day doesn't matter.

Here's what I tried to do in my script:

jour=`date +%d`
mois=`date +%m`
annee=`date +%Y`


    FILE="/appli/project/echanges/RTY/receptions/Rejet_${annee}${mois}"_*


    if [[ -e $FILE  ]]
    then
            echo "FILE EXISTS"
    else
            echo "FILE DOES NOT EXIST"

    fi
  • The wildcard you tried doesn't actually match the files you wanted to find. Maybe use `...${mois}??"_*` – tripleee Mar 06 '19 at 12:21

2 Answers2

0

You have the directory path and the file pattern that you are looking for.

The ls command can be used to list files based on patterns. All commands return an integer value after execution. 0 means the execution finished successfully. Any non-zero value means error.

ls will return a non-zero value if no files match the pattern.

That return code you can use within the if statement.

#!/bin/bash

jour=`date +%d`
mois=`date +%m`
annee=`date +%Y`
/appli/project/echanges

dir="/appli/project/echanges/RTY/receptions"
file_prefix="Rejet_DAP_"


if ls $dir/${file_prefix}${annee}${mois}* > /dev/null 2>&1
then
        echo "FILE EXISTS"
else
        echo "FILE DOES NOT EXIST"
fi

The #!/bin/bash line is called a shebang line and I highly recommend using it in your scripts.

The > /dev/null 2>&1 is so that you don't get output from the ls command and only have your output displayed.

Community
  • 1
  • 1
parml
  • 497
  • 5
  • 15
-1

You can use find for this

$ if [[ `find /appli/project/echanges/RTY/receptions/ -type f |grep -i Rejet_DAP_${annee}${mois}|wc -l` -gt 0 ]] ; then 
 echo "FILE EXISTS"
else
 echo "FILE DOES NOT EXIST"
fi
Sonny
  • 3,083
  • 1
  • 11
  • 19