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
Source: Tips4all
Bash has a "not" logical operator, which is the exclamation point (similar to many other languages). Try this:
ReplyDeleteif [ ! -f /tmp/foo.txt ];
then
echo "File not found!"
fi
You can negate an expression with "!":
ReplyDelete#!/bin/bash
FILE=$1
if [ ! -f $FILE ]
then
echo "File $FILE does not exists"
fi
The relevant manpage is "man test".
if [[ ! -a $FILE ]]; then
ReplyDeleteecho "$FILE does not exist!"
fi
Also, it's possible that the file is a broken symbolic link. If you want to catch that you should:
if [[ ! -a $FILE ]]; then
if [[ -L $FILE ]]; then
echo "$FILE is a broken symlink!"
else
echo "$FILE does not exist!"
fi
fi
I've found this list of bash conditional statements very useful.
ReplyDeleteIf you type "man test" it will show you all the syntax for the "[ ]" (test) in bash.
ReplyDeleteIt's worth mentioning that if you need to execute a single command you can abbreviate
ReplyDeleteif [ ! -f $file ]; do echo $file;fi
to
test -f $file || echo $file
You should be careful about running test for unquoted variable, because it might produce unexpected results:
ReplyDelete$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1
The recommendation is usually to have the tested variable surrounded by double quotation marks:
#!/bin/bash
FILE=$1
if [ ! -f "$FILE" ];
then
echo "File $FILE does not exist."
fi
Keep in mind, I'm only considering Bash. This is how I prefer to do a one liner, I actually use this syntax even for a couple commands.
ReplyDelete# [ /$DIR/$FILE ] || echo "$FILE NOT FOUND"
# [ /$DIR/$FILE ] && echo "$FILE FOUND"
For a couple commands, like I would do in a script.
# [ /$DIR/$FILE ] || { echo "$FILE NOT FOUND" ; exit 1 ;}
Once I started doing this, rarely use the fully typed syntax!!
you can use -z , eg
ReplyDeleteif [ -z `which grep` ] ;then echo "Missing grep"; fi