I've used the following script to see if a file exists:
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
What's the correct syntax to use if I only want to check if the file does not exist?
#!/bin/bash
FILE=$1
if [ $FILE does not exist ]; then
echo "File $FILE does not exist."
fi
You can do this:
or
If you want to check for file and folder both, then use
-e
option instead of-f
.-e
returns true for regular files, directories, socket, character special files, block special files etc.The test command (
[
here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:sometimes it may be handy to use && and || operators.
Like in (if you have command "test"):
or
You should be careful about running
test
for an unquoted variable, because it might produce unexpected results:The recommendation is usually to have the tested variable surrounded by double quotation marks:
Also, it's possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:
Bash File Testing
-b filename
- Block special file-c filename
- Special character file-d directoryname
- Check for directory Existence-e filename
- Check for file existence, regardless of type (node, directory, socket, etc.)-f filename
- Check for regular file existence not a directory-G filename
- Check if file exists and is owned by effective group ID-G filename set-group-id
- True if file exists and is set-group-id-k filename
- Sticky bit-L filename
- Symbolic link-O filename
- True if file exists and is owned by the effective user id-r filename
- Check if file is a readable-S filename
- Check if file is socket-s filename
- Check if file is nonzero size-u filename
- Check if file set-user-id bit is set-w filename
- Check if file is writable-x filename
- Check if file is executableHow to use:
A test expression can be negated by using the
!
operator