bash check if file exists

 If a directory exists:

if [ -d "$DIRECTORY" ]; then  # Control will enter here if $DIRECTORY exists.fi

If a directory doesn’t exist:

if [ ! -d "$DIRECTORY" ]; then  # Control will enter here if $DIRECTORY doesn't exist.fi

One thing to keep in mind:

[ ! -d "$DIRECTORY" ] will be true either

  1. if $DIRECTORY doesn’t exist, or
  2. if does exist but isn’t a directory.

Consider something like

if [ ! -d "$DIRECTORY" ] ; then       mkdir "$DIRECTORY" ;  fi;

this will fail if "$DIRECTORY" is a file. (Of course, you should check whether mkdir succeeded anyway; there are a number of reasons it can fail.)


Example:

file="foo" if [[ -e "$file" ]]; then    echo "File Exists"; fi;