Linux / UNIX: Delete a file

Posted on in Categories , , , , last updated April 24, 2015

How do I delete a file under Linux / UNIX / BSD / AIX / HP-UX operating system using command line options?

To remove a file or directory in Linux, FreeBSD, Solaris or Unix-like operating systems use the rm command or unlink command.

rm command syntax

rm (short for remove) is a Unix / Linux command which is used to delete files from a filesystem. Usually, on most filesystems, deleting a file requires write permission on the parent directory (and execute permission, in order to enter the directory in the first place). The syntax is as follows to delete the specified files and directories:

rm {file-name}
rm [options] {file-name}
unlink {file-name}
rm -f -r {file-name}

Where,

  • -f: Forcefully remove file
  • -r: Remove the contents of directories recursively

When rm command used just with the file names, rm deletes all given files without confirmation by the user.

Remove or Delete a File Example

To remove a file called abc.txt type the following command:
$ rm abc.txt

To remove three files named foo.mp4 bar.doc demo.txt

rm foo.mp4 bar.doc demo.txt
ls

To remove all files & subdirectories from a directory (MS-DOS deltree like command), enter:
$ rm -rf mydir

To request confirmation before attempting to remove each file pass the -i option to the rm command:
$ rm -i filename
Sample outputs:

Gif 01: rm command demo
Gif 01: rm command demo

A note about deleting empty directories

To remove empty directory use rmdir and not the rm command:
$ rmdir mydirectory
$ rmdir dirNameHere

Read a List of All Files To Delete From a Text File

The rm command is often used in conjunction with xargs to supply a list of files to delete. Create a file called file.txt:
$ cat file.txt
List of to delete:

file1
/tmp/file2.txt
~/data.txt

Now delete all file listed in file.txt, enter:
$ xargs rm < file.txt

How do I delete a file named -foo.txt or a directory named -bar?

The syntax is as follows to to delete a file called -foo.txt:
rm -- -foo.txt
OR
rm -- ./-foo.txt
The syntax is as follows to to delete a directory called -bar:
rm -r -f -- -bar
The two -- dashes tells rm command the end of the options and rest of the part is nothing but a file or directory name begins with a dash.

Never run rm -rf / as an administrator or normal UNIX / Linux user

WARNING! These examples will delete all files on your computer if executed.

$ rm -rf /
$ rm -rf *

rm -rf (variously, rm -rf /, rm -rf *, and others) is frequently used in jokes and anecdotes about Unix disasters. The rm -rf / variant of the command, if run by an administrator, would cause the contents of every writable mounted filesystem on the computer to be deleted. Do not try these commands.

See also:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

110 comment

  1. Will you please tell me the command(in unux/linux) which delete the content of directory without deleteing the directory itself.
    other than rm -rf(it will delete directory too) that i dont want.

  2. It should be:

    rm -f path/to/my/directory/*

    Since in linux files doesn’t need file extension. Also, if you want to remove folders inside you have to add the -r flag.

  3. Hi UNIX expert,

    For the command referred to, can a user with world-writeable permission uses the command to remove directories in O/S? Can a user remove a whole directory even though he/she does not have world-writeable permission to the files under the directories?

    Thank you so much.

  4. How to remove all the files and directory inside a /usr/local/www/squid/myfolder directory but not remove directory /usr/local/www/squid/ using rm command?

  5. how to delete a file which is being generated on its own.
    have deleted the source from which its generating but its still generating the file.
    have tried all th commands like rm & rm -f still no effect. please help

  6. Hi,
    I’m a linux user, I have a directory called “projects” in which there are number of subdirectories, my problem is that I have a directory called “CVS” in every sub-directory (within “projects”) which I want to delete using CLI (command line interface). Is it possible to use one command (or may be very few commands) to find and delete the “CVS” directory?
    Thanks

    1. Use this:

      find /var/www2/ -depth -name ‘CVS’ -exec rm -rf ‘{}’ \; -print

      where /var/www2/ is the location you want to recursively go through…

  7. Hi
    i need one help. iam having one file in ftp server after processing the file will be chaged how to write that command….

  8. I have a folder, lets call it a. Inside of a, is another folder (b) and some files. What command would I use to delete all the files inside of the a folder, but not touch b?

    I tried what I saw above, rm !() but was not sure..i put the name of the path of folder b inside the brackets. I then tried, just the letter b… all to no avail.

    Thanks.

  9. How can I delete the content of the file without opening the file?
    I used the “echo -n > YOURFILE” but another file with the same name created.

  10. Hi,
    Could someone help me in preparing a script to delete a file from a directory after the completion of a process(Informatica job)?

    Thank you.

  11. I am getting an error that says root directory is full. How do I safely remove all the contents of this directory. Do I need to do a copy backup first???
    Thanks
    Rick

  12. I need to deleate some data from the UNIX file but am not able to do that.Can anyone please help me out on this?
    Thanks
    amit

    1. for deleting or writing data in files. follow this
      1. type vi “yourfilename”
      (now the content in your file will be disply as a word file)
      2. now you can use two commands to delete data
      a.place the curser in the line, press dd(d twice) to delete one line.
      b.place curser in the character and press x to delete character.
      nb : for moving (placeing) curser use h, j, k , l .. to go up,down, sides ..

      hope this will help you … this is just a basic way
      if u want to learn more command to edit files … try search for “unix vi” . there are lots of results avaible there

    1. Warning: Test this on a NON production computer/server or in a dummy directory before you run it.

      This assumes that you want to start the delete process on files that had date
      stamp starting 09-10-2010 @ 12:00 AM and ending 09-18-2010 23:59
      If not, modify the startdate and enddate accordingly.

      #!/bin/sh

      startdate=”201009010000″
      enddate=”201009182359″
      touch -t $startdate ./startdatefiles
      touch -t $enddate ./enddatefiles
      find ./ -type f -newer ./startdatefiles ! -newer ./enddatefiles -ls

      Once you test the above script and find it listing the files that needed to be deleted correctly, add -exec rm “{}” \; argument to complete the task.

      You can also modify it to change the startdate and enddate variables programatically and even use this in your crontab to automate the process.

      Hope this helps.

  13. Hi,
    I want to create script for the following scenario:

    The requirements are as below:-

    1.) Create a cash script to remove STDF files with invalid lot ID.
    2.) Script to be created > /ebsxe/ebs25/users/test/script
    3.) Directory of the files > /ebsxe/ebs25/users/test/STDF4

    The examples of files in STDF4:
    S_20101202044129_MQB021M_B11P_N.st4__ba5651-s_BTS721L1_BAT
    S_20101202031130_MQB010J_Q11P_N.st4__ba5651-s_BTS721L1_BAT
    S_20101213061928_2_B11P_N.st4__ba56513-s_S1098C3F_BAT

    4.) If the character between 2nd underscore and 3rd underscore (eg:MQB021M, MQB010J, 2) less than 8 character, it must be delete automatically.

    Kindly please help.

  14. Q:What is commnd to delete all the information in file’s with out deleting file in a directory.

    I know only with echo command we can delete all the information in one file.
    A directory contain 10 files. I need to delete all the information which is in those file and files should be there in that directory with ZERO memory Size.

    Thanks & Reards,

    1. Try a shell loop. In this example, cd to /data/files directory and run the command on all .txt files:

      cd /data/files
      for f in *.txt
      do
         >"$f"
      done
  15. hi, i have a folder, where some production files are automatically creates and after a few time it will be automatically delets. what my job is, to copy down all the new files created before it been deleted … i am facing a problem sometimes i am in otherjobs so i cant copy files. i am losing files. so will anybody here please help me to write a script to copy all the files to another dictionary. which runs in every 15 min. all the files have a common extension “.ser”
    thanks in advance

  16. Hi Experts ,

    The comments are really helpful. may i know how to delete files by year?i have one dir containts 33million files. i want to delete it by year start from 2009…plz help

    1. Hi vickram,

      Take a look at my response to another post here by jestin dated January 21, 2011.
      All you have to do is just specify the dates.

  17. How can I remove a unix file of the type #payroll.txt# ? I tried : rm #payroll.txt#, but it tells me that I have to supply more arguments. Any suggestion?
    Thanks,
    Phil

  18. Phil,
    The reason you are getting that error is because of the #.

    Try the following.
    rm \#payroll.txt\# (you can force it not to prompt you by specifying -f)
    If you have files with numbers in them, you can always consider ?* wildcards.

  19. How can I delete bunch of text file. I want to delete file for perticular range like
    xxx24mar2010.txt to xxx30mar2010.txt. Please suggest.

  20. Hi,

    I have created a long list (>4.000 entries) of redundant files that need to be deleted. Typing the command:
    xargs rm < iTunesDeleteList

    produces an error message:
    xargs: unterminated quote.

    I tried to replace spaces with "\ " but it didn't work. What should I do to make it work?Typical entry:
    /Users/me/Music/iTunes/iTunes Media/Music/B.B. King/King Of The Blues [Disc 1]/1-23 Don't Answer The Door, Parts One And Two 1.mp3

    Thanks,
    Andrej

  21. write a shell program to delete all directory which has been created before a perticular date e.g. 3 rd jun 2010

    1. 1. Make a copy of the file.
      2. Run the following.

      $ sort myfile.txt | uniq -uc

  22. Hi
    When i am trying to delete a files using rm,rm -f,rm -rf the files still exists in the directory.. I tried deleting it by changing permissions but not done.. Any help is appreciated

    1. Try changing user or group ownership using chown for the files in question and then delete them again.

  23. How to delete few different files using unix rm command. I want to delte thousands of files which are older than 6 months.
    Below i gave the command which i have been using the files. But it does work.
    Command:
    find /My Dir -name ‘1309927_sat_0407.price.xls 131011719_sat_0807.price.xls’ -mtime +180 -exec rm -f {} \;

    Please help me.

      1. Satheesh,

        See my post @ January 21, 2011 (scroll up to see it) and modify the startdate and startdate for your usage.

  24. Hi ,

    After ls -lrt in a directory , it will give around 300 files with the most recently created/used file at the bottom. I want to delete the top 120 files from the directory. Can you please help. Thanks :)

  25. I have a problem that I need a solution to.

    How can I find the largest file and remove it with naming the file in Linux/Unix?

    Any help would be appreciated.

  26. is it possible for rm command to list what files are being deleted without being in interactive mode

    for example if I want to delete contents of a directory

    rm /directory/*

    is there a way to list which files are being deleted WHILE they’re being deleted?

    1. While this article discusses deleting files, to answer your question.
      Deleting line(s) matching pattern
      sed ‘/pattern/d’

      If you know the line number already, or you can use cat -n to display it, then delete the lines based on the line numbers.

      For example to delete lines 2 and 4 from file example.txt
      sed -e ‘2d;4d’ example.txt

  27. HI : I need to delete all files named .0001 on my server ? Would this work rm *.0001 ???
    thanks ..

    1. If you can’t delete a file using rm -f (r not needed unless if you are deleting directories), then sudo rm or su – root and then delete the file.
      If that does not work, or if you get Operation not permitted, try unsetting the immutable attribute.
      chattr -i file.txt
      And then try again.

  28. How to install tar.bz2 and tar.gz2
    How to uninstall tar.bz2 and tar.gz2 .
    please help me…

  29. I want to delete a user in solaris but when trying to delete it is showing that user is already logged in how to delete that user.

  30. How to remove “delete” option for file ?

    What i mean to say is, even though i am a root user, the file should not have permission even for me to delete it.

    1. chattr +i myfile
      Will prevent anyone including root from deleting the file.

      chattr -i myfile
      Will remove that restriction.

      man chattr for more details.

  31. I need to delete a directory with a $ symbol in front of it, using rm commands has not worked any suggestions?

  32. To remove files without directory, try this.

    find | xargs rm

    It will remove only file not directory itself.

  33. Hi,

    I want to schedule a cron job with file created by specific user be deleted every night.

    Any ideas please?

  34. @ Rick.
    Here is a quick a dirty way to do it.
    1. Get a bash script something along this.
    #!/bin/sh
    rm -f /path/to/file

    2. Save the file as something like deletefile.sh
    3. Make it executable.
    chmod +x deletefile.sh

    Make sure the path to file and the file name to be deleted are correct, test before you run this without the -f switch in the script. Run the script manually and see if it is working as expected.

    4. Move it to a directory that only you or root has access to it.

    4. Schedule it to run in Cron.
    crontab -e

    Add something like.
    0 4 * * * /path/to/script/delefile.sh >/dev/null 2>&1

    Remember, Cron syntax is as follows:
    1 2 3 4 5
    m h d month daypofweek
    So the above means the script will run @ 4:00 AM everyday. Change the value accordingly.

    Save the Cron tab fail.

    Or course you can substitute the script by a oneliner in Cron, but the script gives you the ability to enhance this process and check for errors, ..etc.

  35. @ Aram

    Thanks for you reply

    Can you please tell me what does 2>&1 signify in your cron job and like as I want only specific user files to be deleted like for example files created by user1 only

    may be i was not able to get completely from this script.

  36. @Rick
    No problem.
    >/dev/null 2>&1 redirects both stdout and stderr to /dev/null to prevent email/tty notification. You can remove that part but expect to see an email every Cron runs the script.
    Did you try running the script first before adding it to your crontab?If so, what was the output?
    Any errors you see?
    If not, then check under what user you added the entry in crontab. If you added it as anyone other than that specific user, then either give write permission to the directory/file (bad idea), or simply add the crontab entry for that specific user.
    Either use crontab -u user1 -e And then add the entry, or su user1 and then run crontab -e to add the entry.
    Either way, make sure that the script is running under a user that has write access to that file/directory.
    If you see errors, please post them here.

  37. Aram

    Thanks a lot for your help. It was tested successfully with your help!!!
    I am a newbie, it was of great help to me

      1. Aram,

        I have another question for you. I want to set a cronjob which should be doing following:
        checking a error file if generated every night in a specific directory and if there is one then sending to 5 users email id?

        I think this should be done by creating a shell script and scheduling it every night.

        Thanks a lot

        1. Rick,

          Looks like my reply to you was held for moderation and was never released. Probably due to usage of example email addresses. I posted another answer. If you have any questions, please let me know.

  38. Let’s say that your file is named errofile.txt

    Your script would look something like the following:
    #!/bin/sh
    $FILE=”/path/to/errofile.txt” #Change the file name here

    if [ -f $FILE ];
    then
    echo “Error file found. Please see attached” | mutt -a $FILE -s “Error File” — recipient@domain.com recipient2@domain.com recipient3@domain.com recipient4@domain.com recipient5@domain.com
    fi

    Save the above script in a safe directory and make sure the user that the script will run under will have access to it, name it something like errorfile.sh

    Note: To avoid email being rejected, make sure to set .muttrc for that specific user to set envelope from address.
    Add the following lines to .muttrc for the user the script will run under (change address@domain.com to the email address to be used.)

    set from=”address@domain.com”
    set envelope_from=yes

    If .muttrc under the home directory for that user does not exist, just add it.
    touch .muttrc
    nano .muttrc
    And then add the above two lines.
    Save and close.

    Now in your cron, add the entry.
    crontab -e

    0 1 * * * /path/to/script/errorfile.sh >/dev/null 2>&1

    This means that errorfile.sh will run daily at 1:00 AM. Change the time to when you want the script to run.
    Save and exit.

    Before you do anything, manually test.
    If you have any questions, let me know.

  39. Looks like the original reply was held for moderation, not sure why it was not released. Let me try again.

    Rick,

    Let’s say that your file is named errofile.txt

    Your script would look something like the following:
    #!/bin/sh
    $FILE=”/path/to/errofile.txt” #Change the file name here

    if [ -f $FILE ];
    then
    echo “Error file found. Please see attached” | mutt -a $FILE -s “Error File” — recipient1 recipient2 recipient3 recipient4 recipient5
    fi

    Replace each recipient with the full email for each one.
    Save the above script in a safe directory and make sure the user that the script will run under will have access to it, name it something like errorfile.sh

    Note: To avoid email being rejected, make sure to set .muttrc for that specific user to set envelope from address.
    Add the following lines to .muttrc for the user the script will run under (change sender to the email address to be used.)

    set from=”sender”
    set envelope_from=yes

    If .muttrc under the home directory for that user does not exist, just add it.
    touch .muttrc
    nano .muttrc
    And then add the above two lines.
    Save and close.

    Now in your cron, add the entry.
    crontab -e

    0 1 * * * /path/to/script/errorfile.sh >/dev/null 2>&1

    This means that errorfile.sh will run daily at 1:00 AM. Change the time to when you want the script to run.
    Save and exit.

    Before you do anything, manually test.
    If you have any questions, let me know.

  40. Hey Aram,

    Thanks for your reply. I am testing this. Will reply you soon with. Actually i do not have permission to install mutt on the machine. So making those things work.

  41. Hey Rick,

    If you don’t have permissions to install Mutt, then can you check if you have mail, mailx or sendmail (/var/lib/sendmail/)?
    Depending on what you have installed, we can modify the script(s) to send the email.

  42. Aram,

    Yes I do have var/spool.mail ..

    can you please let me know how to modify this script. Thanks!

  43. Hey Rick,

    Please excuse this delayed response.
    /var/spool/mail access is normal on multi-user system, that is where your email is spooled and processed. I was asking if you have access to any email client software, since you said you don’t have Mutt and don’t have permissions to install it.

    If your admin won’t install/allow installation of Mutt, and this is still unresolved, check if you have any of the of the following.
    Mail
    sendmail

    Depending on what you have installed, replace the line that is sending the email to the recipients with one of the following:

    If you have mail installed:
    Change the line above script that is:

    echo “Error file found. Please see attached” | mutt -a $FILE -s “Error File” — recipient1 recipient2 recipient3 recipient4 recipient5

    To
    gzip -c /path/to/errofile.txt | uuencode /path/to/errofile.txt.gz | mail -s “Error File” recipient1 recipient2 recipient3 recipient4 recipient5 — -f sender@mydomain.com

    If you have sendmail installed, then that line becomes.
    echo -e “Subject: Error file found. Please see attached” | “(cat /path/to/errofile.txt;uuencode attach.file targ.type) | /usr/lib/sendmail -oi addr@server” -f sender@mydomain.com -t tickets@edgecast.com recipient1 recipient2 recipient3 recipient4 recipient5

    Tweak the code as necessary.
    Hope this helps.

  44. Hey Rick,

    Please excuse this delayed response.
    (Also previous comment was held for moderation, probably because of the email addresses in it)
    /var/spool/mail access is normal on multi-user system, that is where your email is spooled and processed. I was asking if you have access to any email client software, since you said you don’t have Mutt and don’t have permissions to install it.

    If your admin won’t install/allow installation of Mutt, and this is still unresolved, check if you have any of the of the following.
    Mail
    sendmail

    Depending on what you have installed, replace the line that is sending the email to the recipients with one of the following:

    If you have mail installed:
    Change the line above script that is:

    echo “Error file found. Please see attached” | mutt -a $FILE -s “Error File” — recipient1 recipient2 recipient3 recipient4 recipient5

    To
    gzip -c /path/to/errofile.txt | uuencode /path/to/errofile.txt.gz | mail -s “Error File” recipient1 recipient2 recipient3 recipient4 recipient5 — -f sender

    If you have sendmail installed, then that line becomes.
    echo -e “Subject: Error file found. Please see attached” | “(cat /path/to/errofile.txt;uuencode attach.file targ.type) | /usr/lib/sendmail -oi addr@server” -f sender -t recipient1 recipient2 recipient3 recipient4 recipient5

    Tweak the code as necessary.
    Hope this helps.

  45. hi

    plz suggest how to delet a rar file from ftp server.

    i use the comand rm -f file name to delet the file but after run this command out put come like
    rm: cannot remove `BAMBackup.rar’: Disk quota exceeded.

  46. Hello,

    Suppose I have multiple files on a folder and I want to delete only the files that contains the word ‘hello’. How to do it ? Thank you

    1. There are several ways to do that, the easiest way is to use find.
      First make sure you see the expected files in the results here.
      find -type f -exec grep -q ‘hello’ {} \; -print

      If you are not seeing anything unusual, run this.

      find -type f -exec grep -q ‘hello’ {} \; -delete

  47. can i delete files under the mounted filesystem? for example

    /myFS

    can i delete all files under this?

    # rm -rf /myFS

    would it delete all files?

    and also

    does rm -rf / really delete all files your on your system?

  48. Thank you for the tutorial.

    Worked perfectly on the SSL certs I needed to delete and replace.

    Vincent Polisi

  49. How do I create a “Cron Job” on the Cpanel?
    I’d like to DELETE all files in the folder “infos”
    in directory “public_html” every Saturday 23:59.
    They all are in “mp3” format!

    Path:
    /public_html/infos

    How do I create the task in Cron on Cpanel to
    be performed in my website?

  50. How can i write script to delete all files and stay last week files only .

    for example :
    i need manual script to delete all files before 2/5/2016 and all files after 2/5 will not delete and this script will work weekly .

    Thanks

    1. hey M. Altell i think you mean to say that you want to delete files before 2/5/2016.

      just run this command,
      find . -not -newermt 2016-05-02 -exec rm -v {} \;

      Hope it helps :-)

  51. Is there a way to search the entire file system and delete all files with ‘part of filename’ in all directories?

Comments are closed.