Skip to content
Related Articles

Related Articles

Improve Article

Shell Script to Delete a File from Every Directory Above the Present Working Directory

  • Last Updated : 28 Jul, 2021

In this article, we will discuss how to delete a file from every directory above the parent working directory using shell script in Linux. To delete a file from a directory we use the rm command in Linux/UNIX

Syntax:

rm [OPTION]... [FILE]...

Using shell script, we have to delete the input file from every directory above the present working directory. The filename will be passed as an argument. The following diagram shows the tree structure of the desktop directory.

In the above image, we are currently present in the /Desktop directory. 



  • Present working Directory can be seen using the pwd command
  • In the tree structure in the above diagram, we have a GFGfile.txt file. GFGfile.txt is a regular text file. 
  • This file is located in 4 directories, namely, GFG, AAAA, BBBB, CCCC. 
  • Now we will go to the “CCCC” directory using the cd command. We will delete the other GFGfile.txt above the present working directory. i.e. All GFGfile.txt will be deleted except the file present in the “CCCC” directory.

Approach:

  1. Initialize flag=1
  2. Initialize homeDir as ‘/home’ directory
  3. Loop until flag becomes 0 else go to step 13.
  4. go to the Previous directory using the “cd ..” command.
  5. set pwd Command to present working directory
  6. remove the file using the rm command
  7. if the present working directory is equal to the home directory then set a flag to 0
  8. Go to step 7
  9. Stop

Below is the implementation.

# check whether arguments are passed or not
if [ $# -eq 0 ]
then
        # if arguments are not passed then display this
        echo "pass the file name"  
        
        # exit the program
        exit 

# end if 
fi 

# store the argument in fileName
fileName=$1 

# set flag
flag=1

# set homeDir to home directory
homeDir=/home 

# loop till flag becomes 1
while [ $flag -eq 1 ] 
do
        # go to previous directory
        cd .. 
        
        # set pwdCommand to present directory
        pwdCommand=`pwd` 
        
        # pint pwd/filename
        echo "$pwdCommand/$fileName" 
        
        # remove the file from present directory
        rm "$pwdCommand/$fileName" 2> /dev/null 
        
        # set flag to 0 if we reach to /home directory
        if [ $pwdCommand = $homeDir ] 
        then 
                flag=0
        
        # end if
        fi
        
# end while
done

Output:

To run the shell script use

./delFile.sh <filename>

Give execution permission to shell script using:

chmod +x delFile.sh

All the GFGfile.txt files have been delete above the present working directory 

My Personal Notes arrow_drop_up
Recommended Articles
Page :