-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
File Testing
-b filename – Block special file
-c filename – Special character file
-d directoryname – Check for directory existence
-e filename – Check for file existence
-f filename – Check for regular file existence not a directory
-G filename – Check if file exists and is owned by effective group ID.
-g filename – true if file exists and is set-group-id.
-k filename – Sticky bit
-L filename – Symbolic link
-O filename – True if file exists and is owned by the effective user id.
-r filename – Check if file is a readable
-S filename – Check if file is socket
-s filename – Check if file is nonzero size
-u filename – Check if file set-user-id bit is set
-w filename – Check if file is writable
-x filename – Check if file is executable
example script,
if a file does not exist
if [ ! -f /tmp/rmohan.txt ]; then
echo “File not found!”
fi
#!/bin/bash
FILE=$1
if [ ! -f “$FILE” ]
then
echo “File $FILE does not exists”
fi
if [[ ! -a $FILE ]]; then
echo “$FILE does not exist!”
fi
Also, it’s possible that the file is a broken symbolic link, or a non-regular file,
like e.g. a socket, device or fifo. If you want to catch that you should:
if [[ ! -a $FILE ]]; then
if [[ -L $FILE ]]; then
echo “$FILE is a broken symlink!”
else
echo “$FILE does not exist!”
fi
fi
To reverse a test, use “!”. That is equivalent to the “not” logical operator in other languages. Try this:
if [ ! -f /tmp/test.txt ];
then
echo “File not found!”
fi
Or written in a slightly different way:
if [ ! -f /tmp/test.txt ]
then echo “File not found!”
fi
Or you could use:
if ! [ -f /tmp/test.txt ]
then echo “File not found!”
fi
Or, presing all together:
if ! [ -f /tmp/test.txt ]; then echo “File not found!”; fi
Which may be written (using then “and” operator: &&) as:
[ ! -f /tmp/test.txt ] && echo “File not found!”
Which looks shorter like this:
[ -f /tmp/test.txt ] || echo “File not found!”
echo “entre file”
read a
if [ -s /home/rmohan/$a ]
then
echo “yes file is there ”
else
echo “soryy file is not there”
fi
if [ true ]
then
# do something here
fi
Very important: Make sure you leave spaces around the bracket characters.
I’ll show more detailed tests as we go along.
Linux shell file-related tests
To perform tests on files use the following comparison operators:
-d file Test if file is a directory
-e file Test if file exists
-f file Test if file is an ordinary file
-r file Test if file is readable
-w file Test if file is writable
-x file Test if file is executable
Recent Comments