Table of Contents

How to Check if File or Directory Exists in Bash Shell

Scripting in Bash is fun. In this post, I would talk about how to check if a file or director exits. Lets start with the file first

ls credits.csv
credits.csv

I have the above file credits.csv. Lets check if the credits.csv file using Bash

How to check if file exists in bash

if [[ -f "credits.csv" ]]; then
    echo "file exists"
fi
file exists

Lets go over the above if loop. Bash is very space sensitive. Check out the space between brackets. Lets try the above command by removing the spaces.

if [[-f "credits.csv" ]]; then
    echo "file exists"
fi
bash: [[-f: command not found

We got the error that [[-f: command not found. so make sure you fix the spaces.

We can also use -e switch to check if file exists. -e can be used for both file and directory

if [[ -e "credits.csv" ]]; then
    echo "file exists"
fi
file exists

How to check if file not exists in bash. We will have to use the negate argument. Lets try that.

if [[ ! -e "credits.csv" ]]; then
    echo "file doesnt exist"
else
    echo "file exists"
fi
file exists

How to Check if file is symbolic link to a file in bash

Lets create a symbolic link to our credits.csv.

ln -s credits.csv creditslink
ls -lrt creditslink
lrwxrwxrwx 1 root root 11 Nov 30 00:19 creditslink -> credits.csv

Ok we have now the symbolic link in place. Lets check this link using bash script.

if [[ -L "creditslink" && -f "creditslink" ]]
then
    echo "creditslink is a symlink to a file"
fi
creditslink is a symlink to a file

As you see above, we combined both the switches -L for symbolic link and -f for checking the file using the && operator

How to check if directory exists in bash

Lets check if home directory exists. The command is pretty much same except that instead of -f use -d switch

if [[  -d "/home" ]]; then
    echo "directory home exists"
else
    echo "directory home doesn't exist"
fi
directory home exists

We can also use -e switch to check if directory exists

if [[  -e "/home" ]]; then
    echo "directory home exists"
else
    echo "directory home doesn't exist"
fi
directory home exists

How to Check if file is symbolic link to a directory in bash

Lets create a symbolic link to directory home.

pwd
/home/projects/notebooks
ln -s  /home homelink
ls -lrt homelink
lrwxrwxrwx 1 root root 5 Nov 30 00:15 homelink -> /home

Ok we have created the symbolic link now. Now lets check if it is a symbolic link to a directory.

if [[ -L "homelink" && -d "homelink" ]]
then
    echo "homelink is a symlink to a directory"
fi
homelink is a symlink to a directory

Thats it for now. Hope the above commands, you would find helpful.

Related Topics:

symlink linux linux create symbolic link remove soft link

Related Posts