Search code examples
shellcommand-linesh

.sh file to check if file exists with dynamic name


I created a sample .sh file with script like this:

if [ -f "/Spool/Cognos/Cognos.xlsx" ]
then 
    echo "File exists"

else
  echo "File not exists"
fi

However, I would like to change so that it could read file with dynamic names, the files that will be uploaded in the folder /Spool/Cognos will be something like this: Cognos Aug24.xlsx, Cognos Sep24.xlsx, Cognos July24.xlsx, etc.

How can I change the if part of the script above? I tried if [ -f "/Spool/Cognos/Cognos*.xlsx" ] with * as wildcard but it seems like it does not work.


Solution

  • You can do it like this:

    for f in /Spool/Cognos/Cognos*.xlsx; do
      if [ -f "$f" ]; then
        echo File exists
      else
        echo File not exists
      fi
      break
    done
    

    If you don't mind overwriting the positional parameters, this will also work:

    set -- /Spool/Cognos/Cognos*.xlsx
    if [ -f "$1" ]; then
      echo File exists
    else
      echo File not exists
    fi