Browse All Articles > Find out File and Directory Exist with Conditional Expressions
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"
Comments (0)