Bash Shell: a method to test the existence of a file or directory
This article is about Bash Shell: a way to test whether a file or directory exists. The editor thought it was very practical, so I shared it with you as a reference. Let's follow the editor and have a look.
1. Bash shell: test whether the file exists
If we need to add something or need to create a file from a script. First, make sure that the file already exists. For example, one of my scripts creates a log in file/tmp/testfile.log, and we need to make sure that the file exists.
#! / bin/bash if [- f / tmp/testfile.log] then echo "File exists" fi
The above statements can also be written using the test keyword, as follows
#! / bin/bash if test-f / tmp/testfile.logthen echo "File exists" fi
Or we can write something like this on one line. This is very useful when writing shell scripts.
[- f / tmp/testfile.log] & & echo "File exists"
Add other parts to the above command
[- f / tmp/testfile.log] & & echo "File exists" | | echo "File not exists"
2. Bash shell: test whether the directory exists
Sometimes we need to create files in a specific directory, or we need a directory. We should all make sure that the directory exists. For example, we now check to see if / tmp / mydir exists.
#! / bin/bash if [- d / tmp/mydir] then echo "Directory exists" fi
The above statements can also be written using the test keyword, as follows
#! / bin/bash if test-d / tmp/mydirthen echo "Directory exists" fi
Or on one line we can write something like this
[- d / tmp/mydir] & & echo "Directory exists"
3. Bash Shell: create a file directory if it does not exist
This is the best way to check for the existence of a file before creating it, otherwise you may receive an error message. This is useful when creating files or directories required by shell scripts at run time.
File:
[!-f / tmp/testfile.log] & & touch / tmp/testfile.log
Table of contents:
1 [!-d / tmp/mydir] & & mkdir-p / tmp/mydir Thank you for reading! About Bash Shell: the method of testing the existence of files or directories is shared here. I hope the above content can be helpful to you so that you can learn more knowledge. If you think the article is good, you can share it and let more people see it.