<

Find out File and Directory Exist with Conditional Expressions

Published on
7,594 Points
4,594 Views
Last Modified:
With the help of BASH shell and IF command it is possible to find out if file exists or not. Generally, this is known as conditional expressions. Conditional expressions are used by the [][] compound command and the test and [] builtin commands to test file attributes and perform string and arithmetic comparisons. General syntax:
[] parameter FILE ]
OR
test parameter FILE
Where parameter can be any one of the following:
-e: Returns true value if file exists
-f: Return true value if file exists and regular file
-r: Return true value if file exists and is readable
-w: Return true value if file exists and is writable
-x: Return true value if file exists and is executable
-d: Return true value if exists and is a directory
Examples
Find out if file /etc/passwd file exists or not
Type the following commands:
 
$ [ -f /etc/passwd ] && echo "File exists" || echo "File does not exists"
$ [ -f /tmp/fileonetwo ] && echo "File exists" || echo "File does not exists"

Open in new window


Find out if directory /var/logs exists or not
Type the following commands:
 
$ [ -d /var/logs ] && echo "Directory exists" || echo "Directory does not exists"
$ [ -d /dumper/fack ] && echo "Directory exists" || echo "Directory does not exists"

Open in new window


You can use conditional expressions in a shell script:
 
#!/bin/bash
FILE=$1
 
if [ -f $FILE ];
then
   echo "File $FILE exists"
else
   echo "File $FILE does not exists"
fi

Open in new window


Save and execute the script:
$chmod  x script.sh
$./script.sh /path/to/file
$./script.sh /etc/resolv.conf

Open in new window

0
Comment
0 Comments

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

Join & Write a Comment

Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month