- Bash — Check Directory
- Bash scripting Check if the directory exists
- How to Verify if a File or Directory Exists in Bash
- Introduction to the Test Command in Bash
- Verifying if a File Exists in Bash
- Checking if a Directory Exists in Bash
- Checking if a File Does Not Exist
- Checking if Multiple Files Exist
- File Test Operators
- Best Practices for Checking File or Directory Existence in Bash
- 1. Always Quote Your Variables
- 2. Use -e for General Existence Check
- 3. Prefer [[ Over [ or test
- 4. Check for Non-existence
- 5. Use Logical Operators for Multiple Conditions
- 6. Handle Errors Gracefully
- 7. Keep It Simple and Readable
- Conclusion
- How To Check If File or Directory Exists in Bash
- How to Check if a File Exists
- How to Check if a Directory Exists
- How to Check if a File Does not Exist
- How to Check for Multiple Files
- File Test Operators to Find Prticular Types of Files
- Working with Code Snippets
Bash — Check Directory
Bash scripting tutorials on programming examples for checking directory exists or not multiple directories check, files exist, the directory does not exist, create a directory ternary and if statements, directory write and executable permissions.
In this tutorial, the Bash script checks whether a directory exists or not.
Bash scripting Check if the directory exists
if then the block is used to test conditional expression of the directory
—check directory exists and prints the message. The conditional expression contains the -d option and directory path. -d option which checks for a directory exists or not.
Please note that add space after [ and before -d .
In this example, using an if-else conditional block.
- Checked if the directory exists using -d .
- else block will have a code for not existing and create a directory using the directory path
—Check directory exists using ternary syntax
Alternatively, the ternary conditional expression uses in place of if conditional expressions.
Here is an example conditional expression
- Check if multiple directories exist Sometimes, We want to check that multiple directories exist.
We have to use if conditional statements with logical AND operator(&&).
– Check directory exists and is writable and executable
- folder exists or not
- if exists, the Folder has permission to write and executable.
- Finally, Print a string message
– Check files or directory exists
Sometimes, we want to check if the file or directory exists. -e option checks for file or directory for the given path exists or not.
How to Verify if a File or Directory Exists in Bash
When working with Bash scripts, it’s a common requirement to check if a file or directory exists before performing an operation. This guide will provide you with a comprehensive understanding of how to perform these checks in Bash, focusing on the test command and its various forms.
Introduction to the Test Command in Bash
The test command is a built-in function in Bash that evaluates conditional expressions. It’s a fundamental tool for checking file types and comparing values. The test command can be written in three syntax forms:
For scripts that need to be portable across different shells, it’s recommended to use the traditional test or [ command, which is available on all POSIX shells. The modern version of the test command, [[ (double brackets), is supported on most contemporary systems using Bash, Zsh, and Ksh as default shells.
Verifying if a File Exists in Bash
When you need to confirm if a file exists, Bash provides the -e and -f FILE operators. The -e operator checks if a file exists, regardless of its type, while -f returns true only if the file is a regular file (not a directory or a device).
Here’s an example of how you can use the test command with an if statement to check if a file exists:
FILE=/path/to/your/file if test -f "$FILE"; then echo "$FILE exists." fi
You can also use the [ or [[ forms:
FILE=/path/to/your/file if [ -f "$FILE" ]; then echo "$FILE exists." fi FILE=/path/to/your/file if [[ -f "$FILE" ]]; then echo "$FILE exists." fi
To perform different actions based on whether the file exists or not, use the if/then construct:
FILE=/path/to/your/file if [ -f "$FILE" ]; then echo "$FILE exists." else echo "$FILE does not exist." fi
Always use double quotes to avoid issues when dealing with files containing whitespace in their names.
You can also use the test command without the if statement. The command after the && operator will only be executed if the exit status of the test command is true:
test -f /path/to/your/file && echo "$FILE exists." [ -f /path/to/your/file ] && echo "$FILE exists." [[ -f /path/to/your/file ]] && echo "$FILE exists."
Opposite to && , the statement after the || operator will only be executed if the exit status of the test command is false:
[ -f /path/to/your/file ] && echo "$FILE exist." || echo "$FILE does not exist."
Checking if a Directory Exists in Bash
The -d operator allows you to test whether a file is a directory or not. For example, to check whether the /etc/docker directory exists, you would use:
DIR=/path/to/your/directory if [ -d "$DIR" ]; then echo "$DIR is a directory." fi [ -d /path/to/your/directory ] && echo "$DIR is a directory."
You can also use the double brackets [[ instead of a single one [ .
Checking if a File Does Not Exist
Similar to many other languages, the test expression can be negated using the ! (exclamation mark) logical not operator:
FILE=/path/to/your/file if [ ! -f "$FILE" ]; then echo "$FILE does not exist." fi [ ! -f /path/to/your/file ] && echo "$FILE does not exist."
Checking if Multiple Files Exist
Instead of using complicated nested if/else constructs, you can use -a (or && with [[ ) to test if multiple files exist:
if [ -f /path/to/your/file1 -a -f /path/to/your/file2 ]; then echo "Both files exist." fi if [[ -f /path/to/your/file1 && -f /path/to/your/file2 ]]; then echo "Both files exist." fi
Equivalent variants without using the IF statement:
[ -f /path/to/your/file1 -a -f /path/to/your/file2 ] && echo "Both files exist." [[ -f /path/to/your/file1 && -f /path/to/your/file2 ]] && echo "Both files exist."
File Test Operators
The test command includes the following FILE operators that allow you to test for particular types of files:
- -b FILE – True if the FILE exists and is a special block file.
- -c FILE – True if the FILE exists and is a special character file.
- -d FILE – True if the FILE exists and is a directory.
- -e FILE – True if the FILE exists and is a file, regardless of type (node, directory, socket, etc.).
- -f FILE – True if the FILE exists and is a regular file (not a directory or device).
- -G FILE – True if the FILE exists and has the same group as the user running the command.
- -h FILE – True if the FILE exists and is a symbolic link.
- -g FILE – True if the FILE exists and has set-group-id (sgid) flag set.
- -k FILE – True if the FILE exists and has a sticky bit flag set.
- -L FILE – True if the FILE exists and is a symbolic link.
- -O FILE – True if the FILE exists and is owned by the user running the command.
- -p FILE – True if the FILE exists and is a pipe.
- -r FILE – True if the FILE exists and is readable.
- -S FILE – True if the FILE exists and is a socket.
- -s FILE – True if the FILE exists and has nonzero size.
- -u FILE – True if the FILE exists, and set-user-id (suid) flag is set.
- -w FILE – True if the FILE exists and is writable.
- -x FILE – True if the FILE exists and is executable.
Best Practices for Checking File or Directory Existence in Bash
When writing Bash scripts that involve checking the existence of files or directories, it’s important to follow some best practices to ensure your scripts are robust, reliable, and easy to maintain.
1. Always Quote Your Variables
When dealing with filenames, always enclose your variables in double quotes. This prevents issues with filenames that contain spaces or special characters. For example:
FILE="/path/with spaces/file.txt" if [ -f "$FILE" ]; then echo "$FILE exists." fi
2. Use -e for General Existence Check
If you just need to check whether a file or directory exists, regardless of its type, use the -e operator. This can simplify your code and make it more readable.
3. Prefer [[ Over [ or test
The [[ command is a more modern and powerful version of [ and test . It supports more operators and is less prone to scripting errors. For example, it doesn’t word-split variable expansions.
4. Check for Non-existence
Sometimes, it’s more efficient to check for non-existence of a file or directory. For example, before creating a directory, check if it doesn’t already exist:
DIR="/path/to/dir" if [ ! -d "$DIR" ]; then mkdir "$DIR" fi
5. Use Logical Operators for Multiple Conditions
If you need to check multiple conditions, use logical operators like -a (AND) and -o (OR). This can make your code cleaner and easier to understand.
6. Handle Errors Gracefully
If a file or directory doesn’t exist, make sure your script handles this gracefully. Don’t assume that a file or directory will always exist.
7. Keep It Simple and Readable
Lastly, always aim for simplicity and readability in your scripts. Use clear variable names, add comments to explain what your code does, and organize your code in a logical way. This will make your scripts easier to maintain and debug.
Conclusion
This guide has provided a comprehensive overview of how to check if a file or directory exists in Bash. By understanding and utilizing the test command and its various forms, you can create more robust and reliable Bash scripts. Remember, practice is key when it comes to mastering these concepts, so don’t hesitate to try out these examples on your own.
How To Check If File or Directory Exists in Bash
Note: You may encounter the term bash script. This is a sequence of several commands to the shell. A script can be saved as a file and is often used to automate multiple system commands into a single action.
How to Check if a File Exists
To test for the file /tmp/test.log, enter the following from the command line:
The first line executes the test to see if the file exists. The second command, echo, displays the results 0 meaning that the file exists, 1 means no file was found.
In our example, the result was 1.
Now try creating a file, then testing for it:
As we have created the file beforehand, the result now is 0:
You can also use square brackets instead of the test command:
How to Check if a Directory Exists
To check if a directory exists, switch out the –f option on the test command for –d (for directory):
Create that directory, and rerun the test:
This command works the same as it does for files, so using brackets instead of the test command works here also.
Note: If you are searching for a file or directory because you need to delete it, refer to our guide on removing files and directories with Linux command line.
How to Check if a File Does not Exist
Typically, testing for a file returns 0 (true) if the file exists, and 1 (false) if the file does not exist. For some operations, you may want to reverse the logic. It is helpful if you write a script to create a particular file only if it doesn’t already exist.
To create a file if one doesn’t already exist, enter the following at a command line:
[ ! –f /tmp/test.txt ] && touch /tmp/test.txt
The exclamation point ! stands for not. This command makes sure there is not a file named test.txt in the /tmp directory. You won’t see anything happen.
To see if the system created the file, enter the following:
You should see test.txt listed. You can use a similar command for a directory – replace the –f option with –d:
[ ! –d /tmp/test ] && touch /tmp/test
How to Check for Multiple Files
To test for two files at the same time use the && option to add a second file:
[ -f /tmp/test.txt && -f /tmp/sample.txt ] && echo “Both files were found”
To test for multiple files with a wildcard, like an asterisk * to stand for various characters:
[ -f /tmp/*.jpg ] && echo “Files were found”
As usual, changing the –f option to –d lets you run the same test for multiple directories.
File Test Operators to Find Prticular Types of Files
Here are several commands to test to find specific types of files:
There are many other options available. Please consult the main page (test ––help) for additional options.
Working with Code Snippets
The previous commands work well for a simple two-line command at a command prompt. You can also use bash with multiple commands. When several commands are strung together, they are called a script.
A script is usually saved as a file and executed. Scripting also uses logical operators to test for a condition, then takes action based on the results of the test.
To create a script file, use the Nano editor to open a new file:
Enter one of the snippets from below, including the #!/bin/bash identifier. Use Ctrl-o to save the file, then Ctrl-x to exit Nano. Then, run the script by entering:
The following code snippet tests for the presence of a particular file. If the file exists, the script displays File exists on the screen.
#!/bin/bash if [ -f /tmp/test.txt ] then echo “File exists” fi
This works the same if you’re checking for a directory. Just replace the –f option with –d:
#!/bin/bash if [ -d /tmp/test ] then echo “File exists” fi
This command checks for the directory /tmp/test. If it exists, the system displays File exists.
You can now use bash to check if a file and directory exist. You can also create simple test scripts as you now understand the functions of a basic bash script file. Next, you should check out our post on Bash Function.