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 filei and a subdirectory diri under the current directory. Assume that filei has a permission of r-x (read and execute permission) and diri has a permission of rwx (read, write, and execute permission). The code for the shell program would look like this:

#!/bin/sh if [ -d $diri ]; then echo "diri is a directory" else echo "diri is not a directory"

fi if [ -f $dir1 ]; then echo "diri is a regular file" else echo "diri is not a regular file"

fi if [ -r $filei ]; then echo "filei has read permission" else echo "filei does not have read permission"

fi if [ -w $filei ]; then echo "filei has write permission" else echo "filei does not have write permission"

fi if [ -x $diri ]; then echo "diri has execute permission" else echo "diri does not have execute permission"

If you execute the shell program, you get the following results:

diri is a directory filei is a regular file filei has read permission filei does not have write permission diri has execute permission

Was this article helpful?

0 0

Post a comment