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 if
and switch
. In this example we will check if file named myinput.py
exists.
有条件的用法中最好使用方括号格式,例如if
和switch
。 在此示例中,我们将检查名为myinput.py
文件myinput.py
存在。
$ if [ -f myinput.py ]; then echo "File Exist"; fi
检查文件是否不存在(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 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 test
keyword 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 $?
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
linux bash文件