Bash: Determine state of file


Following you will find some tests one can perform on a file to identify its state

Check if file $FILE does not exist

if [ ! -f "$FILE" ]; then
    echo "File $FILE does not exist";
fi

Check if file $FILE exists and is a directory

if [ -d "$FILE" ]; then
    echo "File $FILE exists and is a directory";
fi

Check if file $FILE exists and is a regular file (not a directory)

if [ -f "$FILE" ]; then
    echo "File $FILE exists and is a regular file (not a directory)";
fi

Check if file $FILE exists, we do not know what type it is (if it is a directory, socket, node, etc.)

if [ -e "$FILE" ]; then
    echo "File $FILE exists, we do not know what type it is (if it is a directory, socket, node, etc.)";
fi

Check if file $FILE exists and is a symbolic link

if [ -L "$FILE" ]; then
    echo "File $FILE exists and is a symbolic link";
fi

Check if file $FILE exists and is a socket

if [ -S "$FILE" ]; then
    echo "File $FILE exists and is a socket";
fi

Check if file $FILE exists and is not empty

if [ -s "$FILE" ]; then
    echo "File $FILE exists and is not empty";
fi

Check if file $FILE exists and is readable

if [ -r "$FILE" ]; then
    echo "File $FILE exists and is readable";
fi

Check if file $FILE exists and is writable

if [ -w "$FILE" ]; then
    echo "File $FILE exists and is writable";
fi

Check if file $FILE exists and is executable

if [ -x "$FILE" ]; then
    echo "File $FILE exists and is executable";
fi

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.