0

Currently I'm writing a script and I need to check if a certain file exists in a directory without knowing the extension of the file. I tried this:

if [[ -f "$2"* ]]

but that didn't work. Does anyone know how I could do this?

KantSpel
  • 81
  • 5

3 Answers3

1

-f expects a single argument, and AFIK, you don't get filename expansion in this context anyway.

Although cumbersome, the best I can think of, is to produce an array of all matching filenames, i.e.

shopt -s nullglob
files=( "$2".* )

and test the size of the array. If it is larger than 1, you have more than one candidate., i.e.

if (( ${#files[*]} > 1 ))
then
  ....
fi

If the size is 1, ${files[0]} gives you the desired one. If the size is 0 (which can only happen if you turn on nullglob), no files are matching.

Don't forget to reset nullglob afterwards, if you don't need it anymore.

user1934428
  • 19,864
  • 7
  • 42
  • 87
1

In shell, you have to iterate each file globbing pattern's match and test each one individually.

Here is how you could do it with standard POSIX shell syntax:

#!/usr/bin/env sh

# Boolean flag to check if a file match was found
found_flag=0

# Iterate all matches
for match in "$2."*; do

  # In shell, when no match is found, the pattern itself is returned.
  # To exclude the pattern, check a file of this name actually exists
  # and is an actual file
  if [ -f "$match" ]; then
    found_flag=1
    printf 'Found file: %s\n' "$match"
  fi
done
if [ $found_flag -eq 0 ]; then
  printf 'No file matching: %s.*\n' "$2" >&2
  exit 1
fi
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
0

You can use find:

find ./ -name "<filename>.*" -exec <do_something> {} \;

<filename> is the filename without extension, do_something the command you want to launch, {} is the placeholder of the filename.

Dominique
  • 16,450
  • 15
  • 56
  • 112