OldWildWeb Logo

Bash Linux check if file exist

Linux Bash: how to check if a file exist


How to check if a file exist, Linux bash

For backups and system administration matters, check if a file exist is one of the most useful test condition with linux bash, here below a very simple example:

#!/bin/bash
if [ ! -f foo.txt ]; then
echo "File not found!"
echo "Content" > foo.txt
else
echo "File Exist!"
fi


Other test condition can be applied here below a list of all available tests:
-b filename - Block special file
-c filename - Special character file
-d directory name - Check for directory Existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID
-G filename set-group-id - True if file exists and is set-group-id
-k filename - Sticky bit
-L filename - Symbolic link
-O filename - True if file exists and is owned by the effective user id
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable

Ultimi articoli