Interview Questions

Shell Script - Find list of Files having Write Permission in a directory

In this section, Let us see how to find the Files which are having Write permission enabled in a particular directory.

In the below script, we are going to find the list of all files inside "/cygdrive/c/Shell_Script" which are having Write permission for the user Owner.

The below script will produce a report.csv file which will have writable files list.

FindFilesHavingWritePermission.sh

# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

#
# Script to find the List of Files which are having Write permission enabled in a directory
#

OUTPUT_FILE=report.csv
echo "Name,Status" > ${OUTPUT_FILE}

cd /cygdrive/c/TechDive/Shell_Script

for i in `find . -type f | grep -v ${OUTPUT_FILE}`
{
        fileName=$i
        permission=`ls -ltr ${fileName} | cut -d" " -f1 | cut -b3`

        if [ "${permission}" = 'w' ]
        then
                echo "${fileName} is Writable"
                echo "${fileName}, Writable" >> ${OUTPUT_FILE}
        fi
}

echo "Refer the Report file ie., report.csv"

Script Execution

$ sh FindFilesHavingWritePermission.sh
./1.txt is Writable
./2.txt is Writable
./3.txt is Writable
Refer the Report file ie., report.csv

Report

$ cat report.csv
Name,Status
./1.txt, Writable
./2.txt, Writable
./3.txt, Writable