The if and test commands are used in conjunction to check whether a file exists or not in Bash. You’ll typically use expressions like -e or -f to check a file’s existence, whereas -d is used in the case of directories.In addition to further info on these, we’ve also detailed how to check if a file exists using wildcards and how to exclusively check if a file doesn’t exist in this article.
Check If File or Directory Exists
First, let’s talk about the primary expressions, i.e., primaries. You can use the man test command to check test’s man page for the full list of primaries, but here are the most commonly used ones:Let’s start with something basic. In the following example, we store the file’s path in $FILE. From the table above, -e means that if FILE exists is true, then the $FILE exists output will be echoed. If FILE doesn’t exist, then the $FILE doesn’t exist will instead be the output that’s echoed.FILE=/file/pathif [[ -e “$FILE” ]]; thenecho “$FILE exists.“elseecho “$FILE doesn’t exist.“fiYou could do the same thing more efficiently as such:test -e /file/path && echo “File exists.” || echo “File doesn’t exist.”You could also use wildcard characters for this:[ -e /file/path ] && echo “File exists.” || echo “File doesn’t exist.”You would use the -d expression to check if a directory exists or not:[ -d /directory/path ] && echo “Directory exists.” || echo “Directory doesn’t exist.”
Check If A File Doesn’t Exist
If you’re only trying to check if the file doesn’t exist, you can use the NOT operator (!) as such:if [ ! -e /file/path ]; thenecho “File doesn’t exist.“fiBut once again, you can do the same thing more efficiently as such:[ ! -e /file/path ] && echo “File doesn’t exist.”
Check if Multiple Files Exist
If you’re trying to check whether multiple files exist or not at once, you can use the -a expression or the && operator.Using -aThe first method is as such:if [ -e /file/one -a -e /file/two ]; thenecho “Both files exist.“fiWhereas a more efficient variant would look like this:[ -e /file/one -a -e /file/two ] && echo “Both files exist.“Using &&The first method is as such:if [[ -e /file/one && -e /file/two ]]; thenecho “Both files exist.“fiAn equivalent variant would look like this:[[ -e /file/one && -e /file/two ]] && echo “Both files exist.”
Check If One of Two Files Exists
If you’re trying to check if one of two files exists, you could use the following command:if [ -f /file/path ] || [ ! -f /file/path ] ; then echo Exists; fiIf you’re trying to check if one of two files doesn’t exist, you could instead apply ! to one of the file paths as such:if [ -f /file/path ] || [ ! -f /file/path ] ; then echo Missing; fi