Linux Bash Script Check File Existence

in Categories , , , , , , , , , last updated August 14, 2009

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

[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 999; }
if [ -f $file ];
	echo "File $file exists."
		echo "File $file does NOT exists."

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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 0 comments/add one below):