Shell判断文件是否存在

Shell判断文件是否存在教程

Shell 中,我们要判断一个文件是否存在,可以使用 if 条件判断与 test 命令的 e 参数一起进行判断。

Shell判断文件是否存在详解

语法

if test -e $filename then # else # fi

参数

参数 描述
filename 需要判断的文件

说明

我们使用 if 与 test 命令的 e 参数,可以判断文件是否存在。

案例

Shell判断文件是否存在

使用 test 命令,实现判断文件是否存在

#!/bin/bash echo "pls input filename:" read filename if test -e $filename then echo "文件存在" else echo "文件不存在" fi

程序运行后,控制台输出如下:

05_Shell test判断文件是否存在.png

我们使用了 test 命令与 if 语句,进行了文件是否存在的判断,我们输入了一个存在的文件,此时,if 语句返回了 true,我们继续输入一个不存在的文件,此时控制台输出如下:

06_Shell test判断文件是否存在.png

我们看到,这次输出了文件不存在。

Shell判断文件是否存在总结

在 Shell 中,我们要判断一个文件是否存在,可以使用 if 条件判断与 test 命令的 e 参数一起进行判断。