Bash check if file ExistsMost of the time, we may find a situation where we may need to perform an action that will check whether a file exists or not. In Bash, we can use a 'test command' to check whether a file exists and determine the type of a file. Following are the syntaxes of the test command, and we can use any of these commands: We are required to use a single bracket '[' command to make our script portable for all POSIX shells. The upgraded version of the test command contains double brackets '[[' which is supported on most of the modern systems using Bash, Zsh, and Ksh as a default shell. Check If File ExistsWhile checking if a file exists, the most commonly used file operators are -e and -f. The '-e' option is used to check whether a file exists regardless of the type, while the '-f' option is used to return true value only if the file is a regular file (not a directory or a device). The most common option to check if the file exists or not is to use the test command with the 'if conditional statement'. Following are the examples to check whether the 'read_file.txt' file exists: Method 1 Method 2 Method 3 Output Output for all the three methods will be as below because we have a file (read_file.txt) present in the directory: read_file.txt exist If we want to perform an action which will provide a result based on whether the file exists or not, we can use the if/then construct in the following way: Example Output read_file.txt exist We can also use the test command without the if statement. We can use any of the following methods: Method 1 Method 2 Method 3 Output Output for all the three methods will be as below because we have a file (read_file.txt) present in the directory: read_file.txt exist If there are several commands to be run after the && operator, then enclose the commands in curly brackets separated by semicolon(;) or AND (&&), i.e.: Example Unlike &&, the statement after the || operator is executed only if the exit status of the test command is 'false'. Example Output read_file.txt exist These are the commonly used methods in Bash to check whether the file exists or not. Check If Directory ExistsThe operator '-d' allows us to test whether a file is a directory or not. Following are the methods to check whether the 'Javatpoint' directory exists: Method 1 Method 2 Note: We can also use double brackets '[[' instead of a single bracket '['.Output Output for both the above methods will be as below as we have a directory (named Javatpoint) present in the specified location: Javatpoint is a directory Check IF File does not ExistThe test expression can be negated by using the exclamation mark (! -logical NOT operator). Check out the following example: Example Above script can also be written as below: Output missing_read_file.txt unavailable File Test OperatorsThe test commands include the following File Operators which allow us to test for particular types of files:
Next TopicBash Check if Variable is Set
|