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
The test command ([
here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
More succinctly: [ ! -f /tmp/foo.txt ] && echo "File not found!"
I struggled a bit to find the right syntax for "if any of 2 files does not exist". The following both work:
if [ ! \( -f "f1" -a -f "f2" \) ] ; then echo MISSING; fi
if [ ! -f "f1" ] || [ ! -f "f2" ] ; then echo MISSING; fi
@DavidWinterbottom Even more succulently:
[ -f /tmp/foo.txt ] || echo "File not found!"
Parameter can be any one of the following:
-e: Returns true value, if file exists
-f: Return true value, if file exists and regular file
-r: Return true value, if file exists and is readable
-w: Return true value, if file exists and is writable
-x: Return true value, if file exists and is executable
-d: Return true value, if exists and is a directory
There is an asymmetry in using
! -f
with&&
versus using-f
with||
. This has to do with the exit code returned by the non/existence check. If you need your line to always exit cleanly with exit code 0 (and sometimes you don't want this constraint), the two approaches are not interchangeable. Alternatively, just use anif
statement and you no longer have to worry about the exit code of your non/existence check.