Bash—测试文件或目录是否存在

时间:2019-05-19 01:25:35  来源:igfitidea点击:

在使用bash编程时,我们常常需要检查文件是否已经存在、创建新文件、在文件中插入数据。
有时我们还需要从其他脚本执行其他脚本。

本文介绍了如何判断系统中文件或目录是否存在。
这对我们编写shell脚本非常有帮助。

1.bash测试文件是否存在

如果我们需要添加一些内容或需要从脚本创建文件。
首先,确保文件已经存在或不存在。
例如,我在文件 **/tmp/testfile中创建日志的脚本。
我们需要确定这个文件存在与否

#!/bin/bash

if [ -f /tmp/testfile.log ]
then
    echo "File exists"
fi

上面的语句也可以使用下面的关键字 test来编写

#!/bin/bash

if test -f /tmp/testfile.log
then
    echo "File exists"
fi

或者在单行中,我们可以这样写。
这在使用shell脚本编写时非常有用。

[ -f /tmp/testfile.log ] && echo "File exists"

在上面的命令中添加其他部分

[ -f /tmp/testfile.log ] && echo "File exists" || echo "File not exists"

2.bash脚本测试目录是否存在

有时我们需要在特定的目录中创建文件,或者由于其他原因需要目录,我们应该确保该目录存在。
例如,我们检查 /tmp/mydir是否存在。

#!/bin/bash

if [ -d /tmp/mydir ]
then
    echo "Directory exists"
fi

上面的语句也可以使用下面的关键字 test来编写

#!/bin/bash

if test -d /tmp/mydir
then
    echo "Directory exists"
fi

或者在单行中,我们可以这样写

[ -d /tmp/mydir ] && echo "Directory exists"

3. shell中,如果不存在,则创建文件/目录

这是在创建文件之前检查文件存在性的最佳实践,否则我们将得到一条错误消息。
这在创建运行时创建文件或目录所需的shell脚本时非常有用。

如果是文件:

[ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log

如果是目录:

[ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir