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

时间:2020-03-05 15:31:35  来源:igfitidea点击:

如果我们正在使用与文件和目录互动的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语句。

例如,我们可以用两个方括号写入它,保持"然后"在与分号的帮助下与"如果"相同的行,如下所示:

#!/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语句中不使用Square括号的情况非常相同:

#!/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 for目录。

#!/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