0
FILE=*.tf
if [ -f "$FILE" ]; then
> echo "$FILE exists."
> else
> echo "$FILE does not exist."
> fi
does not exist.

The directory Im running this in has a file myfile.tf in it.

Im wondering why this isnt finding the myfile.tf file - could it be because im using the * asterisk wildcard ? What am I doing wrong here?

Thanks

Jshee
  • 2,620
  • 6
  • 44
  • 60
  • Pathname expansion is not performed on variable assignment statements or double-quoted strings. `FILE=*.tf; [ -f "$FILE" ]` will return 1 unless there is a file named `*.tf` in the current directory. – oguz ismail Dec 31 '20 at 16:29

1 Answers1

2

Wildcard will give you a list.

Using bash:

exist_files() {
  ext="${1}"
  for file in *."${ext}"; do
    [[ -f $file ]] && return 0
  done
  return 1
}

if exist_files "tf"; then
  echo "File matching *.tf exists"
else
  echo "File matching *.tf doesn't exists"
fi
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
  • Thanks for the answer. Can you put this in if/else form? Thanks so much – Jshee Dec 31 '20 at 16:04
  • `Can you put this in if/else form?` `if at_least_one_file=0; for file in *.tf; do [[ -f file ]] && at_least_one_file=1; done; [[ $at_least_one_file -lt 1 ]]; then .... fi` – KamilCuk Dec 31 '20 at 16:11
  • `[[ $(exist_files "tf") == "yes" ]]` ugh, that's horrible. Instead: `exist_files() { ... return 0; ... return 1; }`and just `if exist_files "tf"; then ... fi` – KamilCuk Dec 31 '20 at 16:13
  • @Jshee I've updated my answer to make a more friendly function that you can use in an if/else statement (and which is a little bit more optimized because it stop the loop when it find the first occurence that match) – Idriss Neumann Dec 31 '20 at 16:14
  • @KamilCuk I agree in this simple case ^^ (I've updated my answer before reading your comments) but sometimes I prefer to make it a clear difference between `$?` as a potential error/exception to handle and a string or boolean result of my functions (`return 1` != `return true` but more like a `throw new SomeException()`). – Idriss Neumann Dec 31 '20 at 16:18
  • In such cases, you have 255 numbers to choose from. It's a convention typical - `[` returns 0 on true, `1` on false and 2 on error. – KamilCuk Dec 31 '20 at 16:23
  • 1
    @KamilCuk Yes I understand, it's a problem of confidence because I'm used to use programs which don't always follow those conventions (puppet for example). So I'm a little paranoid. And sometimes it can be felt even in simple problems. I know that is not a good thing (so it's for this reason I've updated my answer :p ). – Idriss Neumann Dec 31 '20 at 16:28
  • Question for OP @IdrissNeumann - does this recurse into subdirs? – Jshee Dec 31 '20 at 18:09
  • @Jshee nope but in that case, `find` is your friend :) – Idriss Neumann Dec 31 '20 at 18:47