In this article, We will learn how to list all files in the current directory that have Red, Write and Execute permission.
Suppose, we have the following files in our current directory :
Here, We have a total of 8 files in our current directory. Out of 8, we have Read, Write and Execute permission on 6 files and 2 have only Read and Write permissions.
Let’s write the script for List the Files that have Read, Write and Execute Permissions
- We have to check every file in the current directory and display the name that has Read, Write and Execute permission,
- To traverse through all files, we will use for loop
for file in *
Here, we are using * which represent all files in current working directory and we are storing the current file name on file variable.
- Now we will check whether the chosen file is actually a file or not using if statement
- If it is a file, then we will check whether it has Read, Write and Execute permission,
- We will use an if statement to check all permissions.
- If the file has all permissions then we will print the file name to the console.
- Close the if statement
- If it is not a file, then we will close the if statement and move to the next file.
Before moving forward we will see what these operators do :
- -f $file -> returns true if file exists.
- -r $file -> returns true if file has Read permission
- -w $file -> returns true if file ha write permission.
- -x $file -> returns true if file has Executed permission.
- -a -> it is used for checking multiple conditions, same as && operator.
Below is the implementation:
# Shell script to display list of file names # having read, Write and Execute permission echo "The name of all files having all permissions :" # loop through all files in current directory for file in * do # check if it is a file if [ -f $file ] then # check if it has all permissions if [ -r $file -a -w $file -a -x $file ] then # print the complete file name with -l option ls -l $file # closing second if statement fi # closing first if statement fi done
Now, our code writing work is done but still, we can’t run our program because when we create a file in Linux, It has two permissions i.e Read and Write for the User who created the file. To execute our file, we must give the Execute permission to the file.
Assigning Execute permission to main.sh:
$ chmod 777 main.sh
Use the following command to run the script:
$ bash main.sh