Search code examples
bashfile-ioscripting

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


This checks if a file exists:

#!/bin/bash

FILE=$1     
if [ -f $FILE ]; then
   echo "File $FILE exists."
else
   echo "File $FILE does not exist."
fi

How do I only check if the file does not exist?


Solution

  • The test command (written as [ here) has a "not" logical operator, ! (exclamation mark):

    if [ ! -f /tmp/foo.txt ]; then
        echo "File not found!"
    fi