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.
file
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.
chmod 777 filename
Example:
In the following example we are setting the permission of helloworld.txt file.
$ chmod 755 helloworld.txt
-e
-r
-w
-x
-s
-d
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
$ 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
$ sh example03.sh File exists! File is readable. File is writable. File is executable.