如何在Bash脚本中检查特定目录中是否存在文件?

8

我一直试图做的事情都没有成功。如果我想要检查文件是否存在于~/.example目录中

FILE=$1
if [ -e $FILE ~/.example ]; then
      echo "File exists"
else
      echo "File does not exist"
fi

在测试中写下您想要检查的路径。您想要检查 $FILE ~/.example 文件吗? - Etan Reisner
我们如何检查位于 /home/tmp 目录中的 *.txt 文件? - Bhagesh Arora
3个回答

13
你可以使用$FILE与目录拼接,生成完整的路径如下。
FILE="$1"
if [ -e ~/.myexample/"$FILE" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi

1
这应该可以做到:

FILE=$1
if [[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]]; then
      echo "File exists and not a symbolic link"
else
      echo "File does not exist"
fi

它会告诉你是否在忽略符号链接的情况下,$FILE 存在于 .example 目录中。
你也可以使用这个:
[[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]] && echo "Exists" || echo "Doesn't Exist"

这个特别测试它是否是一个普通文件。OP问题中的“-e”测试任何具有正确名称的内容,例如可能是一个目录。 - Kenster
感谢澄清,@Kenster,我将文件视为普通文件,尽管OP使用了-e。也许在这种情况下他指的是文件和文件夹。 - Jahid

1
晚来了,但是一个简单的解决方案是使用-f。
if [[ ! -f $FILE]]
then
  echo "File does not exist"
fi

如果您感兴趣,这里还有更多示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接