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

如果您正在处理与文件和目录交互的 Bash 脚本,您可能会遇到需要确保文件或目录存在的情况。 这有助于避免对不存在的文件执行某些操作时可能出现的错误。

在本教程中,我将向您展示几种检查文件或目录是否存在于 bash 脚本与否。 让我们先从文件开始。

检查文件是否存在于 bash 脚本

这里的想法是使用 -f 运算符,仅当它是常规文件(而不是目录)时才返回 true。

假设您要检查文件 /home/user/my_file 是否存在。 这是使用方括号进行检查的方法

#!/bin/bash
 
if [ -f /home/user/my_file ]
then
    echo "My file exists"
fi

但是您不会总是事先得到文件名,对吗? 您可以将它放在一个变量中,如果是这种情况,您可以以这种方式使用它。

#!/bin/bash

FILE=/home/user/my_file
 
if [ -f "$FILE" ]
then
    echo "My file exists"
else 
    echo "My file doesn't exist"
fi

基本上,重要的是您在 if 命令中使用的条件。 如何使用 if 语句取决于您。

为了 example,你可以用两个方括号来写它,在分号的帮助下将’then’与’if’保持在同一行,如下所示:

#!/bin/bash

FILE=/home/user/my_file
 
if [ -f "$FILE" ]; then
    echo "My file exists"
else 
    echo "My file doesn't exist"
fi

或者像这样把整个语句放在一起:

[ -f /home/user/my_file ] && echo "My file exists" || echo "My file doesn't exist"

检查文件是否存在于 bash 有测试

您也可以使用测试 bash 查看文件是否存在。 只是在 if 语句中不使用方括号几乎是一样的:

#!/bin/bash

FILE=/home/user/my_file
 
if test -f "$FILE" 
then
    echo "My file exists"
else 
    echo "My file doesn't exist"
fi

您也可以像这样在单行中使用上面的代码:

test -f /home/user/my_file && echo "My file exists" || echo "My file doesn't exist"

检查文件是否不存在 bash 脚本

如果反过来,你想检查文件是否不存在怎么办? bash? 通过使用否定运算符,您可以使用与上面几乎相同的代码:

#!/bin/bash

FILE=/home/user/my_file
 
if [ ! -f "$FILE" ]
then
    echo "My file doesn't exist"
fi

现在您知道如何处理文件了,让我们继续讨论目录。

检查目录是否存在于 bash 脚本

检查目录的代码与您在上一节中看到的代码相同。 唯一的区别是您将使用 -d 而不是 -f。 -d 仅对目录返回 true。

#!/bin/bash
 
if [ -d /home/user/my_dir ]
then
    echo "My directory exists"
fi

你也可以在这里使用测试:

#!/bin/bash

DIR=/home/user/my_dir
 
if test -d "$DIR" 
then
    echo "My directory exists"
else 
    echo "My directory doesn't exist"
fi

检查目录是否不存在 bash

您可以再次使用否定来检查目录是否不存在:

#!/bin/bash

DIR=/home/user/my_dir
 
if [ ! -d "$DIR" ]
then
    echo "My directory doesn't exist"
fi

就是这样。 这就是检查文件目录是否存在于 bash 壳与否。

我希望你能找到这个 bash 提示有用。 如果您有任何问题或建议,请随时在下面发表评论。