Often when shell scripting with BASH you need to test if a file exists (or doesn’t exist) and take appropriate action. This post looks at how to check if a file exists with the BASH shell.
To test if the /tmp/foo.txt file exists, you would do the following, changing the echo line to whatever action it is you want to take:
if [ -f /tmp/foo.txt ] then echo the file exists fi
Note that there must be whitespace between the "if" and "[", the "[" and "-f" and the filename and the closing "]" otherwise you will get error messages along the lines of:
[-f: command not found [: missing `]' No such file or directory syntax error near unexpected token `then'
If you want to do something if the file exists and something else if the file doesn’t then you can use an "else" clause like so, again changing the echo line to some other suitable action:
if [ -f /tmp/foo.txt ] then echo the file exists else echo the file does not exist fi
And finally, if you want to check if a file does not exist, then you can do this:
if [ ! -f /tmp/foo.txt ] then echo the file does not exist fi
Again, you need to make sure there is white space on either side of the !, otherwise you’ll get error messages like this:
[!-f: command not found [!: command not found [: !-f: unary operator expected
And finally, if you want to do the same sorts of tests to see if a directory exists using the BASH shell, the use the -d flag instead, e.g.:
if [ -d /tmp ] then echo the directory exists fi