Warm tip: This article is reproduced from serverfault.com, please click

How do I tell if a regular file does not exist in Bash?

发布于 2009-03-12 14:48:43

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
Questioner
Bill the Lizard
Viewed
0
John Feminella 2014-06-13 22:55:36

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