Test if a file exists with the BASH shell
Posted August 27th, 2008 in Linux/Unix/BSD
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
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
