linux bash文件_如何检查Linux Bash中是否存在文件?

linux bash文件

linux bash文件

Linux bash have different file and directory related functions to create, delete, change and check existence. In this tutorial we will look how to check a file or directory if it exists.

Linux bash具有与文件和目录相关的不同功能,以创建,删除,更改和检查是否存在。 在本教程中,我们将研究如何检查文件或目录(如果存在)。

检查文件存在 (Check File Existence)

We will use bash test mechanism. Bash test mechanism have two formats where we can use followings.

我们将使用bash测试机制。 Bash测试机制有两种格式,我们可以使用以下格式。

  • test -f FILENAME

    测试-f FILENAME
  • [ -f FILENAME]

    [-f FILENAME]

Square brackets format is preferred in conditional usage like ifand switch . In this example we will check if  file named myinput.py exists.

有条件的用法中最好使用方括号格式,例如ifswitch 。 在此示例中,我们将检查名为myinput.py文件myinput.py存在。

$ if [ -f myinput.py ]; then echo "File Exist"; fi
Check File Existence
Check File Existence
检查文件存在

检查文件是否不存在(Check If File Not Exist)

Another use case it checking existing and returning the reverse answer or NOT’ing the Boolean result. If the file exist this will return not in if conditional. We will use ! which is used by programming languages for Boolean reversing. In this example if the file named “myfile” do not exist we will print message.

另一个用例是检查现有情况并返回相反的答案或不给出布尔结果。 如果文件存在, if有条件时将不返回。 我们会用! 编程语言将其用于布尔反转。 在此示例中,如果名为“ myfile”的文件不存在,我们将打印消息。

$ if [ ! -f myfile ]; then echo "File Do Not Exist"; fi
Check If File Not Exist
Check If File Not Exist
检查文件是否不存在

使用测试命令检查是否存在(Check Existence with test Command)

As we stated previous test is the same with [ -f FILE] . It just provides a bit different syntax. We will use testkeyword with -f and file name. In this example we will check file named myinput.py and print result with $?.

如前所述,先前的test[ -f FILE]相同。 它只是提供了一些不同的语法。 我们将使用带有-f和文件名的test关键字。 在此示例中,我们将检查名为myinput.py文件,并使用$?打印结果$?

$ test -f myinput.py
$ echo $?
Check Existence with test Command
Check Existence with test Command
使用测试命令检查是否存在

As we can see the result is which means successful or true .

我们可以看到结果是这意味着成功或true

测试目录是否存在 (Test If Directory Exists)

We can also check given directory existence. We will use -d flag in order to test. In this example we will check if the directory named backup exists.

我们还可以检查给定目录的存在。 我们将使用-d标志进行测试。 在此示例中,我们将检查名为backup的目录是否存在。

$ if [ -d backup ]; then echo "Directory Exists"; fi
Test If Directory Exists
Test If Directory Exists
测试目录是否存在
LEARN MORE  Linux fsck Command Tutorial With Examples
了解更多Linux fsck命令教程和示例

翻译自: https://www.poftut.com/check-file-exists-linux-bash/

linux bash文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值