file-io - bash check if directory exists if not create - How do I tell if a regular file does not exist in Bash?

unix command to check if file exists in a directory / bash / scripting

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

codeforester



Answer #1

It's worth mentioning that if you need to execute a single command you can abbreviate

if [ ! -f "$file" ]; then
    echo "$file"
fi
test -f "$file" || echo "$file"
[ -f "$file" ] || echo "$file"