bash if file exists code example

Example 1: check if file exists bash

FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exists."
else 
    echo "$FILE does not exist."
fi

Example 2: .sh script: check if file exist

#!/bin/bash
if [ -e x.txt ]
then
    echo "ok"
else
    echo "nok"
fi

Example 3: .sh script: check if file exist

# The most readable option when checking whether a file exist or not is
# to use the test command or the old '[' or the new '[[' in combination
# with the if statement.
# Any of the snippets below will check whether the /etc/resolv.conf file
# exists:

FILE=/etc/resolv.conf
if test -f "$FILE"; then
    echo "$FILE exist"
fi

# or

FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exist"
fi

# or

FILE=/etc/resolv.conf
if [[ -f "$FILE" ]]; then
    echo "$FILE exist"
fi

Example 4: bash script if file exists

[ -f /etc/resolv.conf ] && echo "$FILE exists."

Example 5: shell logical and for file existence

if [[ -f $FILE1 ]] && [[ -f $FILE2 ]]; then
    echo "OK"
fi

Example 6: if file exist

file_exists ( string $filename ) : bool