Command to display an arbitrary message if a particular file exists

Solution 1:

Use this simple Bash one-liner:

if [ -e FILENAME ] ; then echo Yes ; fi

The -e check evaluates to true if FILENAME exists, no matter what it is (file, directory, link, device, ...).

If you only want to check regular files, use -f instead, as @Arronical said.

Solution 2:

You can use this simple script:

#!/bin/bash

if [[ -f $1 ]]; then
    echo "Yes"
    exit 0
else
    exit 1
fi

Save it as file-exists.sh. Then, in the Terminal, type chmod +x file-exists.sh.

Use it like: ./file-exists.sh FILE where you replace FILE with the file you want to check, for example:

./file-exists.sh file.txt

If file.txt exists, Yes will be printed to the Terminal, and the program will exit with status 0 (success). If the file does not exist, nothing will be printed and the program will exit with status 1 (failure).

If you're curious why I included the exit command, read on...


What's up with the exit command?

exit causes normal process termination. What this means is, basically: it stops the script. It accepts an optional (numerical) parameter that will be the exit status of the script that called it.

This exit status enables your other scripts to use your file-exists script and is their way of knowing the file exists or not.

A simple example that puts this to use is this script (save it as file-exists-cli.sh):

#!/bin/bash

echo "Enter a filename and I will tell you if it exists or not: "
read FILE
# Run `file-exists.sh` but discard any output because we don't need it in this example
./file-exists.sh $FILE &>> /dev/null
# #? is a special variable that holds the exit status of the previous command
if [[ $? == 0 ]]; then
    echo "$FILE exists"
else
    echo "$FILE does not exist"
fi

Do the usual chmod +x file-exists-cli.sh and then run it: ./file-exists-cli.sh. You'll see something like this:

File exists (exit 0):

➜  ~ ./file-exists-cli.sh 
Enter a filename and I will tell you if it exists or not: 
booleans.py
booleans.py exists

File does not exist (exit 1):

➜  ~ ./file-exists-cli.sh
Enter a filename and I will tell you if it exists or not: 
asdf
asdf does not exist

Solution 3:

In the bash shell on the command line.

if [[ -f /path/to/file ]]; then echo "Yes"; fi

This uses the bash conditional operator -f, and is checking whether the file exists and is a regular file. If you want to test for any files including directories and links then use -e.

This is a great resource for bash conditionals.