Unix
In this tutorial we will learn about file operators in Shell Programming.
We will be using the if statement to perform tests.
And we will be using a variable file
to store the file name and we have set the read, write and execute permission.
Note! To change the file permission use the following command.
$ chmod 755 filename
Or, use chmod 777 filename
if you want to give access to everyone.
Example:
In the following example we are setting the permission of helloworld.txt file.
$ chmod 755 helloworld.txt
Operator | Note |
---|---|
-e | To check if the file exists. |
-r | To check if the file is readable. |
-w | To check if the file is writable. |
-x | To check if the file is executable. |
-s | To check if the file size is greater than 0. |
-d | To check if the file is a directory. |
In the following example we are going to check if helloworld.txt exists.
#!/bin/sh
file="/Users/yusufshakeel/Documents/GitHub/shell-script/example/file/helloworld.txt"
# check
if [ -e $file ]
then
echo "File exists!"
else
echo "File does not exists!"
fi
Output:
$ sh example01.sh
File exists!
#!/bin/sh
file="/Users/yusufshakeel/Documents/GitHub/shell-script/example/file"
# check
if [ -d $file ]
then
echo "Directory exists!"
else
echo "Directory does not exists!"
fi
Output:
$ sh example02.sh
Directory exists!
#!/bin/sh
file="/Users/yusufshakeel/Documents/GitHub/shell-script/example/file/helloworld.txt"
# check
if [ -e $file ]
then
echo "File exists!"
# check readable
if [ -r $file ]
then
echo "File is readable."
else
echo "File is not readable."
fi
# check writable
if [ -w $file ]
then
echo "File is writable."
else
echo "File is not writable."
fi
# check executable
if [ -x $file ]
then
echo "File is executable."
else
echo "File is not executable."
fi
else
echo "File does not exists!"
fi
Output:
$ sh example03.sh
File exists!
File is readable.
File is writable.
File is executable.
ADVERTISEMENT