Bash - Test if file or directory exists

Channel: Linux
Abstract: /bin/bash if test -f /tmp/testfile.logthen echo "File exists"fi Or in a single line we can write it as below. This is very useful while writing in she

While working with bash programming, we many times need to check if a file already exists, create new files, insert data in files. Also sometimes we required executing other scripts from other scripts.

This article has few details about the test if file or directory exists in the system. Which can be very helpful for you while writing shell scripting.

#1. Test if File Exists

If we required adding some content or need to create files from the script. First, make sure that the file already exists or not. For example one of my script creating logs in file /tmp/testfile.log and we need to make sure this file exists or not

#!/bin/bash if [ -f /tmp/testfile.log ] then echo "File exists" fi123456#!/bin/bash if [ -f /tmp/testfile.log ]then    echo "File exists"fi

The above statements can be also written using the test keyword as below

#!/bin/bash if test -f /tmp/testfile.log then echo "File exists" fi123456#!/bin/bash if test -f /tmp/testfile.logthen    echo "File exists"fi

Or in a single line we can write it as below. This is very useful while writing in shell scripting.

[ -f /tmp/testfile.log ] && echo "File exists"1[ -f /tmp/testfile.log ] && echo "File exists"

to add else part in above command

[ -f /tmp/testfile.log ] && echo "File exists" || echo "File not exists"1[ -f /tmp/testfile.log ] && echo "File exists" || echo "File not exists"

#2. Test if Directory Exists

Sometimes we need to create files inside a specific directory or need directory any other reason, we should make sure that directory exists. For example we are checking /tmp/mydir exists for not.

#!/bin/bash if [ -d /tmp/mydir ] then echo "Directory exists" fi123456#!/bin/bash if [ -d /tmp/mydir ]then    echo "Directory exists"fi

The above statements can be also written using the test keyword as below

#!/bin/bash if test -d /tmp/mydir then echo "Directory exists" fi123456#!/bin/bash if test -d /tmp/mydirthen    echo "Directory exists"fi

Or in a single line we can write it as below

[ -d /tmp/mydir ] && echo "Directory exists"1[ -d /tmp/mydir ] && echo "Directory exists"

#3. Create File/Directory if not Exists

This is the best practice to check file existence before creating them else you will get an error message. This is very helpful while creating shell scripts required to file or directory creation during runtime.

For File:

[ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log1[ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log

For Directory:

[ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir1[ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir

Ref From: tecadmin

Related articles