Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 12 Nov, 2021
View Discussion
Improve Article
Save Article

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


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.


  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 ]
        # if arguments are not passed then display this
        echo "pass the file name"  
        # exit the program

# end if 

# store the argument in fileName

# set flag

# set homeDir to home directory

# loop till flag becomes 1
while [ $flag -eq 1 ] 
        # go to previous directory
        cd .. 
        # set pwdCommand to present directory
        # print 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 ] 
        # end if
# end while


To run the shell script use

./ <filename>

Give execution permission to shell script using:

chmod +x

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!