bash 检查目录中是否存在给定文件在通配符上失败

时间:2020-12-31 15:55:46

标签: bash if-statement

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

我运行它的目录中有一个文件 myfile.tf

我想知道为什么这找不到 myfile.tf 文件 - 可能是因为我使用了 * 星号通配符?我在这里做错了什么?

谢谢

1 个答案:

答案 0 :(得分:2)

通配符会给你一个列表。

使用 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
相关问题