views:

11914

answers:

6

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
+27  A: 

Bash 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
John Feminella
Thanks. I hate looking stupid like this, but every example I found online was the one that I gave in the question. :)
Bill the Lizard
The only stupid question is an unasked one. ;)
John Feminella
@John: What color is the australian dinosaur in your house? - if that is not a stupid question, I give up.
Blub
DavidWinterbottom
+15  A: 

You can negate an expression with "!":

#!/bin/bash
FILE=$1

if [ ! -f $FILE ]
then
    echo "File $FILE does not exists"
fi

The relevant manpage is "man test".

unbeknown
Thanks for the relevant man page.
Bill the Lizard
+3  A: 
if [[ ! -a $FILE ]]; then
    echo "$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
guns
+3  A: 

I've found this list of bash conditional statements very useful.

frgtn
Thanks, bookmarked. :)
Bill the Lizard
+1  A: 

If you type "man test" it will show you all the syntax for the "[ ]" (test) in bash.

Paul Tomblin
Actually, if you want to see bash's builtin test construct, you should use 'help test'
guns
A: 

you can use -z , eg

if [ -z `which grep` ] ;then echo "Missing grep"; fi
ghostdog74
Stack Overflow is not a forum. Answers may be reordered due to votes, edits, and other reasons, and thus are not suitable for responding to other answers.
ephemient