Linux Bash Script Check File Existence

by on August 14, 2006 · 0 comments· LAST UPDATED August 14, 2009

in , ,

How do I check if a file called /tmp/foo.txt exists or not using a shell script under Linux operating systems?

You can use test command or [ to check file types and compare values. The -f option check if FILE exists and is a regular file. If it exists it returns true value. You can test it as follows for a shell prompt itself:
$ [ -f /tmp/foo.txt ] && echo "File Exists" || echo "File not found"

Bash Script To Check If a File Exists

#!/bin/bash
file=$1
 
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 999; }
 
if [ -f $file ];
then
	echo "File $file exists."
else
		echo "File $file does NOT exists."
fi

Run it as follows:
$ ./script.sh /etc/resolv.conf
File /etc/resolv.conf exists.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , , , , , , , , , ,

Previous Faq:

Next Faq: