Shell Script to Check if a File Exists

9月 20, 2025
Linux, Shell, ByAI

To check if a file exists in a shell script, you can use the test command or the [ command. Both commands are equivalent, but the test command is more powerful and allows you to perform more complex checks.

Here’s an example using the test command:

if test -e {filename}; then
  echo "File exists"
else
  echo "File does not exist"
fi

Alternatively, you can use the [ command:

if [ -e {filename} ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

In both cases, replace {filename} with the name of the file you want to check.

You can also use the -f option to check if the file exists and is a regular file:

if [ -f {filename} ]; then
  echo "File exists and is a regular file"
else
  echo "File does not exist or is not a regular file"
fi

Similarly, you can use the -d option to check if the file exists and is a directory:

if [ -d {filename} ]; then
  echo "File exists and is a directory"
else
  echo "File does not exist or is not a directory"
fi

These are just a few examples of how you can check if a file exists in a shell script. You can find more options and examples in the test or [ command documentation.

本文共 215 字,上次修改于 Oct 12, 2025,以 CC 署名-非商业性使用-禁止演绎 4.0 国际 协议进行许可。

相关文章

» tar 命令中的绝对路径和相对路径使用注意

» 了解 glob 模式匹配

» Cookie 机制

» JWT 介绍和场景示例

» 旧款 MacBook 改造客厅影视系统