Книга: Fedora™ Unleashed, 2008 edition
File Operators
File Operators
The following operators can be used as file comparison operators:
? -d
— To ascertain whether a file is a directory
? -f
— To ascertain whether a file is a regular file
? -r
— To ascertain whether read permission is set for a file
? -s
— To ascertain whether a file exists and has a length greater than zero
? -w
— To ascertain whether write permission is set for a file
? -x
— To ascertain whether execute permission is set for a file
Assume that a shell program called compare3
is in a directory with a file called file1 and a subdirectory dir1 under the current directory. Assume that file1
has a permission of r-x
(read and execute permission) and dir1
has a permission of rwx
(read, write, and execute permission). The code for the shell program would look like this:
#!/bin/sh
if [ -d $dir1 ]; then
echo "dir1 is a directory"
else
echo "dir1 is not a directory"
fi
if [ -f $dir1 ]; then
echo "dir1 is a regular file"
else
echo "dir1 is not a regular file"
fi
if [ -r $file1 ]; then
echo "file1 has read permission"
else
echo "file1 does not have read permission"
fi
if [ -w $file1 ]; then
echo "file1 has write permission"
else
echo "file1 does not have write permission"
fi
if [ -x $dir1 ]; then
echo "dir1 has execute permission"
else
echo "dir1 does not have execute permission"
fi
If you execute the shell program, you get the following results:
dir1 is a directory
file1 is a regular file
file1 has read permission
file1 does not have write permission
dir1 has execute permission