您的位置  > 互联网

Bash 中如何检查文件或目录是否存在

在 Bash 中,如果一个文件或者是一个任务。 您需要的是数据、文件或文件,并且任何内容都应避免和。

Bash 中有许多文件可用于测试文件,例如文件的 、大小、类型等。 您可以将它们与 [ 或 [[ ,或与 if..else 中的测试一起使用。

这里使用 -e、-f、-d 检查文件是否为 或 :

使用 -e 检查文件或 . 如果路径 是文件、链接或任何其他类型的文件,则为真。

#!/bin/bash
if [ -e /path/to/your/file ]; then
  echo "File or directory exists."
else
  echo "File or directory does not exist."
fi

使用 -f 检查文件的。 仅当路径 和 是文件时才成立。 对于 、链接、文件和其他文件类型,该值将为 false。

#!/bin/bash
if [ -f /path/to/your/file ]; then
  echo "Regular file exists."
else
  echo "Regular file does not exist."
fi

当您想要检查 a 文件而不是任何其他类型的文件时,请使用 -d 。

#!/bin/bash
if [ -d /path/to/your/directory ]; then
  echo "Directory exists."
else
  echo "Directory does not exist."
fi

通过这些,你可以在Linux和Unix上更多的了解。