Rm (Unix)

rm
Original author(s)Ken Thompson, Dennis Ritchie
(AT&T Bell Laboratories)
Developer(s)Various open-source and commercial developers
Initial releaseNovember 3, 1971; 53 years ago (1971-11-03)
Written inC
Operating systemUnix, Unix-like, V, Plan 9, Inferno, KolibriOS, IBM i
PlatformCross-platform
TypeCommand
Licensecoreutils: GPLv3+
Plan 9: MIT License

rm (short for remove) is a basic command on Unix and Unix-like operating systems used to remove objects such as computer files, directories and symbolic links from file systems and also special files such as device nodes, pipes and sockets, similar to the del command in MS-DOS, OS/2, and Microsoft Windows. The command is also available in the EFI shell.[1]

Overview

The rm command removes references to objects from the filesystem using the unlink system call, where those objects might have had multiple references (for example, a file with two different names), and the objects themselves are discarded only when all references have been removed and no programs still have open handles to the objects.

This allows for scenarios where a program can open a file, immediately remove it from the filesystem, and then use it for temporary space, knowing that the file's space will be reclaimed after the program exits, even if it exits by crashing.

The command generally does not destroy file data, since its purpose is really merely to unlink references, and the filesystem space freed may still contain leftover data from the removed file. This can be a security concern in some cases, and hardened versions sometimes provide for wiping out the data as the last link is being cut, and programs such as shred and srm are available which specifically provide data wiping capability.

rm is generally only seen on UNIX-derived operating systems, which typically do not provide for recovery of deleted files through a mechanism like the recycle bin,[2] hence the tendency for users to enclose rm in some kind of wrapper to limit accidental file deletion.

There are undelete utilities that will attempt to reconstruct the index and can bring the file back if the parts were not reused.

History

On some old versions of Unix, the rm command would delete directories if they were empty.[3] This behaviour can still be obtained in some versions of rm with the -d flag, e.g., the BSDs (such as FreeBSD,[4] NetBSD,[5] OpenBSD[6] and macOS) derived from 4.4BSD-Lite2.

The version of rm bundled in GNU coreutils was written by Paul Rubin, David MacKenzie, Richard Stallman, and Jim Meyering.[7] This version also provides -d option, to help with compatibility.[8] The same functionality is provided by the standard rmdir command.

The -i option in Version 7 replaced dsw, or "delete from switches", which debuted in Version 1. Doug McIlroy wrote that dsw "was a desperation tool designed to clean up files with unutterable names".[9]

The command is available as a separate package for Microsoft Windows as part of the UnxUtils collection of native Win32 ports of common GNU Unix-like utilities.[10] KolibriOS includes an implementation of the rm command.[11] The rm command has also been ported to the IBM i operating system.[12]

Syntax

rm deletes the file specified after options are added. Users can use a full path or a relative file path to specify the files to delete. rm doesn't delete a directory by default.[13]rm foo deletes the file "foo" in the directory the user is currently in.

rm, like other commands, uses options to specify how it will behave:

  • -r, "recursive," which removes directories, removing the contents recursively beforehand (so as not to leave files without a directory to reside in).
  • -i, "interactive" which asks for every deletion to be confirmed.
  • -f, "force," which ignores non-existent files and overrides any confirmation prompts (effectively canceling -i), although it will not remove files from a directory if the directory is write-protected.
  • -v, "verbose," which prints what rm is doing onto the terminal
  • -d, "directory," which deletes an empty directory, and only works if the specified directory is empty.
  • --one-file-system, only removes files on the same file system as the argument, and will ignore mounted file systems.

rm can be overlain by a shell alias (C shell alias, Bourne shell or Bash) function of "rm -i" so as to avoid accidental deletion of files. If a user still wishes to delete a large number of files without confirmation, they can manually cancel out the -i argument by adding the -f option (as the option specified later on the expanded command line "rm -i -f" takes precedence). Unfortunately this approach generates dangerous habits towards the use of wildcarding, leading to its own version of accidental removals.

rm -rf (variously, rm -rf /, rm -rf *, and others) is frequently used in jokes and anecdotes about Unix disasters,[14] such as the loss of many files during the production of film Toy Story 2 at Pixar.[15] The rm -rf / variant of the command, if run by a superuser, would cause every file accessible from the present file system to be deleted from the machine.

rm is often used in conjunction with xargs to supply a list of files to delete:

 xargs rm < filelist

Or, to remove all PNG images in all directories below the current one:

 find . -name '*.png' -exec rm {} +

Permissions

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). (Note that, confusingly for beginners, permissions on the file itself are irrelevant. However, GNU rm asks for confirmation if a write-protected file is to be deleted, unless the -f option is used.)[16]

To delete a directory (with rm -r), one must delete all of its contents recursively. This requires that one must have read and write and execute permission to that directory (if it's not empty) and all non-empty subdirectories recursively (if there are any). The read permissions are needed to list the contents of the directory in order to delete them. This sometimes leads to an odd situation where a non-empty directory cannot be deleted because one doesn't have write permission to it and so cannot delete its contents; but if the same directory were empty, one would be able to delete it.[17]

If a file resides in a directory with the sticky bit set, then deleting the file requires one to be the owner of the file.

Protection of the filesystem root

Sun Microsystems introduced "rm -rf /" protection in Solaris 10, first released in 2005. Upon executing the command, the system now reports that the removal of / is not allowed.[18] Shortly after, the same functionality was introduced into FreeBSD version of rm utility.[19] GNU rm refuses to execute rm -rf / if the --preserve-root option is given,[20] which has been the default since version 6.4 of GNU Core Utilities was released in 2006. In newer systems, this failsafe is always active, even without the option. To run the command, user must bypass the failsafe by adding the option --no-preserve-root, even if they are the superuser.

User-proofing

Systems administrators, designers, and even users often attempt to defend themselves against accidentally deleting files by creating an alias or function along the lines of:

alias rm="rm -i"
rm () { /bin/rm -i "$@" ; }

This results in rm asking the user to confirm on a file-by-file basis whether it should be deleted, by pressing the Y or N key. Unfortunately, this tends to train users to be careless about the wildcards they hand into their rm commands, as well as encouraging a tendency to alternately pound y and the return key to affirm removes - until just past the one file they needed to keep.[citation needed] Users have even been seen going as far as "yes | rm files", which automatically inserts "y" for each file. [citation needed]

A compromise that allows users to confirm just once, encourages proper wildcarding, and makes verification of the list easier can be achieved with something like:

if [ -n "$PS1" ] ; then
  rm () 
  { 
      ls -FCsd "$@"
      echo 'remove[ny]? ' | tr -d '\012' ; read
      if [ "_$REPLY" = "_y" ]; then
          /bin/rm -rf "$@"
      else
          echo '(cancelled)'
      fi
  }
fi

It is important to note that this function should not be made into a shell script, which would run a risk of it being found ahead of the system rm in the search path, nor should it be allowed in non-interactive shells where it could break batch jobs. Enclosing the definition in the if [ -n "$PS1" ] ; then ....  ; fi construct protects against the latter.

There exist third-party alternatives which prevent accidental deletion of important files, such as "safe-rm"[21] or "trash".[22]

Maximum command line argument limitation

GNU Core Utilities implementation used in multiple Linux distributions have limits on command line arguments. Arguments are nominally limited to 32 times the kernel's allocated page size. Systems with 4KB page size would thus have a argument size limit of 128KB.[23]

For command-line arguments before kernel 2.6.23, (released on 9 October 2007,) the limits were defined at kernel compile time and can be modified by changing the variable MAX_ARG_PAGES in include/linux/binfmts.h file.[24][25]

Newer kernels[which?] limit the maximum argument length to 25% of the maximum stack limit (ulimit -s). Exceeding the limit would prompt the display of the error message /bin/rm: Argument list too long.[26][clarification needed]

See also

References

  1. ^ "EFI Shells and Scripting". Intel. Retrieved 2013-09-25.
  2. ^ "Unix - Frequently Asked Questions (3/7) [Frequent posting]Section - How do I "undelete" a file?". www.faqs.org.
  3. ^ "rm page from Section 1 of the unix 8th manual". man.cat-v.org.
  4. ^ "RM(1)", FreeBSD-5.4-RELEASE, retrieved February 5, 2015
  5. ^ "RM(1)", NetBSD-2.0, retrieved February 5, 2015
  6. ^ "RM(1)", OpenBSD-3.6, retrieved February 5, 2015
  7. ^ "rm(1): remove files/directories - Linux man page". linux.die.net.
  8. ^ Krzysztof Goj (January 22, 2012). "rm: new option --dir (-d) to remove empty directories". coreutils.git.
  9. ^ McIlroy, M. D. (1987). A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 (PDF) (Technical report). CSTR. Bell Labs. 139.
  10. ^ "Native Win32 ports of some GNU utilities". unxutils.sourceforge.net.
  11. ^ "Shell - KolibriOS wiki". wiki.kolibrios.org.
  12. ^ IBM. "IBM System i Version 7.2 Programming Qshell" (PDF). IBM. Retrieved 2020-09-05.
  13. ^ "rm(1) - Linux manual page". man7.org.
  14. ^ Gite, Vivek. "Linux/UNIX: Delete a file". Nixcraft. Retrieved 24 November 2011.
  15. ^ Panzarino, Matthew (21 May 2012). "How Toy Story 2 Got Deleted Twice, Once on Accident, Again on purpose". TNW | Media. Retrieved 27 September 2022.
  16. ^ "Linux rm command help and examples". ComputerHope. 24 January 2018. Archived from the original on April 16, 2016. Retrieved 24 January 2019.
  17. ^ McElhearn, Kirk (2 January 2014). "Master the command line: Deleting files and folders". Macworld. Retrieved 24 January 2019.
  18. ^ "Meddling in the Affairs of Wizards". Archived from the original on 2016-11-03.
  19. ^ "The previous commit added code to rm(1) to warn about and remove any · freebsd/freebsd@d6b7bd9". GitHub.
  20. ^ "rm invocation (GNU Coreutils)". www.gnu.org.
  21. ^ "Safe-rm in Launchpad". Launchpad.
  22. ^ "andreafrancia/trash-cli". September 12, 2020 – via GitHub.
  23. ^ "How to get around the Linux "Too Many Arguments" limit". Stackoverflow. With the coupling of ARG_MAX to ulim -s / 4 came the introduction of MAX_ARG_STRLEN as max. length of an argument [...] MAX_ARG_STRLEN is defined as 32 times the page size in linux/include/uapi/linux/binfmts.h [...] The default page size is 4 KB so you cannot pass arguments longer than 128 KB [...]
  24. ^ "Linux_2_6_23 - Linux Kernel Newbies". kernelnewbies.org.
  25. ^ "kernel/git/torvalds/linux.git - Linux kernel source tree". git.kernel.org.
  26. ^ ""Argument list too long": Beyond Arguments and Limitations | Linux Journal". www.linuxjournal.com.

Further reading

Read other articles:

Visual artist Njideka Akunyili CrosbyAkunyili Crosby in 2014BornNjideka Akunyili1983Enugu, NigeriaNationalityNigerian, AmericanAlma mater Swarthmore College Pennsylvania Academy of Fine Arts Yale University Notable workI refuse to be InvisibleAwards2017 Genius GrantWebsitehttp://www.njidekaakunyili.com/ Njideka Akunyili Crosby // ⓘ (born 1983) is a Nigerian-born visual artist working in Los Angeles, California.[1] Through her art, Akunyili Crosby negotiates the cultural ter...

 

 

الأرشيدوق كارل دوق تيشن (بالألمانية: Carl von Teschen)‏    معلومات شخصية اسم الولادة (بالألمانية: Carl Ludwig Johann Joseph Laurentius von Österreich pp)‏  الميلاد 5 سبتمبر 1771 [1][2][3]  فلورنسا  الوفاة 30 أبريل 1847 (75 سنة) [1][2][3]  فيينا  مكان الدفن السرداب الإمبراطوري...

 

 

Polish actor and television personality Maciej MusiałMusiał in 2018Born (1995-02-11) 11 February 1995 (age 29)Warsaw, PolandEducationAST National Academy of Theatre Arts in Kraków (2021)OccupationsActortelevision personalityYears active2004–present Maciej Musiał (born 11 February 1995) is a Polish actor, and television personality. Biography The son of actors Andrzej and Anna Musiał,[1] he began his acting career at an early age with a cameo appearance in a 2004 episo...

Untuk kegunaan lain, lihat Arca Durga. DurgaDewi kekuatan dan perlindunganLukisan Durga dibuat oleh Raja Ravi Varma abad ke-10.Nama lainMahishasura Mardini, Marikamba, Bhawani, Dewi Maa, Mata Rani, Adi Sakti , GhattammaDewanagariदुर्गाAfiliasiMahadewi · DewiKediamanManidwipaMantraOm Śrī Durgayai Namah[1]Senjatacakra, sangkakala, trisula, gada, pedang tameng, genta atau busurWahanaSinga dan Harimau[2][3]PustakaDewi-Bhagawatapurana, DewimahatmyaFestivalDur...

 

 

Villers-en-ArgonnecomuneVillers-en-Argonne – Veduta LocalizzazioneStato Francia RegioneGrand Est Dipartimento Marna ArrondissementSainte-Menehould CantoneArgonne Suippe et Vesle TerritorioCoordinate49°01′N 4°56′E / 49.016667°N 4.933333°E49.016667; 4.933333 (Villers-en-Argonne)Coordinate: 49°01′N 4°56′E / 49.016667°N 4.933333°E49.016667; 4.933333 (Villers-en-Argonne) Superficie9,76 km² Abitanti239[1] (2009) Densità2...

 

 

 烏克蘭總理Прем'єр-міністр України烏克蘭國徽現任杰尼斯·什米加尔自2020年3月4日任命者烏克蘭總統任期總統任命首任維托爾德·福金设立1991年11月后继职位無网站www.kmu.gov.ua/control/en/(英文) 乌克兰 乌克兰政府与政治系列条目 宪法 政府 总统 弗拉基米尔·泽连斯基 總統辦公室 国家安全与国防事务委员会 总统代表(英语:Representatives of the President of Ukraine) 总...

Endangered Tupian language of Brazil Not to be confused with the Anambé of Ehrenreich. AnambéNative toBrazilRegionPará, Cairari RiverEthnicity130 Anambé (2000)[1]Native speakers6 (2006)[1]Language familyTupian Tupi–GuaraníXinguAnambéLanguage codesISO 639-3aanGlottologanam1249ELPAnambé of CairaríAnambé is classified as Critically Endangered by the UNESCO Atlas of the World's Languages in Danger Anambé, or more specifically Anambe of Cairari, is a possibly ...

 

 

Rhododendron eudoxum Klasifikasi ilmiah Kerajaan: Plantae (tanpa takson): Tracheophyta (tanpa takson): Angiospermae (tanpa takson): Eudikotil (tanpa takson): Asterid Ordo: Ericales Famili: Ericaceae Genus: Rhododendron Spesies: Rhododendron eudoxum Nama binomial Rhododendron eudoxumBalf. f. & Forrest Rhododendron eudoxum adalah spesies tumbuhan yang tergolong ke dalam famili Ericaceae. Spesies ini juga merupakan bagian dari ordo Ericales. Spesies Rhododendron eudoxum sendiri merupakan ba...

 

 

Частина серії проФілософіяLeft to right: Plato, Kant, Nietzsche, Buddha, Confucius, AverroesПлатонКантНіцшеБуддаКонфуційАверроес Філософи Епістемологи Естетики Етики Логіки Метафізики Соціально-політичні філософи Традиції Аналітична Арістотелівська Африканська Близькосхідна іранська Буддій�...

Kompletter CADC mit Gehäuse, auf den Platinen befinden sich die MP944-Mikroprozessoren Der Central Air Data Computer (zentraler Flugdatencomputer) des Kampfflugzeugs Grumman F-14 – abgekürzt CADC – konnte Höhe, Geschwindigkeit relativ zur Luft (Airspeed), Steiggeschwindigkeit und Mach-Zahl anhand von Sensoreingängen wie Pitot-Statik-System, statischem Druck und Temperatur berechnen. Vor dem CADC waren alle Flugdatencomputer elektromechanische Systeme, wie zum Beispiel in dem Flugzeug ...

 

 

1700s–1950s indigenous pidgin of the coastal southern US MobilianYamáNative toUnited StatesRegionGulf coast and Mississippi ValleyExtinct1950sLanguage familyMuskogean-based pidginLanguage codesISO 639-3modLinguist ListmodGlottologmobi1236 Mobilian Jargon (also Mobilian trade language, Mobilian Trade Jargon, Chickasaw–Choctaw trade language, Yamá) was a pidgin used as a lingua franca among Native American groups living along the Gulf of Mexico around the time of European settlement ...

 

 

Fédération Internationale de l'AutomobileSingkatanFIATanggal pendirian20 Juni 1904; 119 tahun lalu (1904-06-20) (as AIACR)StatusAsosiasi sukarelaTipeFederasi Olahraga untuk Balap mobilTujuanMotorists' issuesMotorsportsKantor pusatPlace de la ConcordeLokasiParis, PrancisWilayah layanan InternasionalJumlah anggota 239 organisasi nasionalBahasa resmi InggrisPrancisItaliaPresidenMohammed bin SulayemBadan utamaGeneral AssemblyAfiliasiFIA InstituteFIA FoundationInternational Olympic Committe...

Zimbabwean footballer Stanley Nyazamba Nyazamba with Columbus Crew in 2009Personal informationDate of birth (1983-01-06) January 6, 1983 (age 41)Place of birth Bulawayo, ZimbabweHeight 6 ft 1 in (1.85 m)Position(s) MidfielderCollege careerYears Team Apps (Gls)2004–2007 Lee Flames (28)Senior career*Years Team Apps (Gls)2007 Cape Cod Crusaders 14 (0)2008 Richmond Kickers 16 (8)2008–2009 Columbus Crew 0 (0)2010 FC Tampa Bay 25 (0)2011–2013 Richmond Kickers 32 (4)Total 8...

 

 

French national television network This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: M6 TV channel – news · newspapers · books · scholar · JSTOR (March 2024) (Learn how and when to remove this message)You can help expand this article with text translated from the corresponding article in French. Click [sh...

 

 

Ilustrasi dalam Alkitab Historiale dari Raja Asa dari Yudea yang menghancurkan berhala-berhala, pada penglihatan Azrya. Azarya (Ibrani: עֲזַרְיָה ‘Ǎzaryāh, Yah telah menolong) adalah seorang nabi yang disebutkan dalam 2 Tawarikh 15. Roh Allah dikisahkan datang kepadanya (ayat 1), dan ia pergi menemui Raja Asa dari Yudea untuk mendorongnya melakukan reformasi. Dalam menanggapi dorongan Azarya, Asa mengadakan sejumlah reformasi yang meliputi penghancuran berhala dan memperbaiki...

Division of the National Collegiate Athletic Association NCAA Division III logo NCAA divisions Division I Division II Division III vte NCAA Division III (D-III) is a division of the National Collegiate Athletic Association (NCAA) in the United States. D-III consists of athletic programs at colleges and universities that choose not to offer athletic scholarships to their student-athletes. The NCAA's first split was into two divisions, the University and College Divisions, in 1956, the College ...

 

 

Mammalian protein found in Homo sapiens CEACAM1Available structuresPDBOrtholog search: P13688%20or%20M0R2K4 PDBe P13688,M0R2K4 RCSB List of PDB id codes2GK2, 4QXW, 5DZL, 4WHDIdentifiersAliasesCEACAM1, BGP, BGP1, BGPI, carcinoembryonic antigen related cell adhesion molecule 1, CEA cell adhesion molecule 1External IDsOMIM: 109770; MGI: 1347246; HomoloGene: 128630; GeneCards: CEACAM1; OMA:CEACAM1 - orthologsGene location (Human)Chr.Chromosome 19 (human)[1]Band19q13.2Start42,507,304 bp ...

 

 

1960 studio album by Walter Davis Jr.Davis CupStudio album by Walter Davis Jr.ReleasedJune 1960[1]RecordedAugust 2, 1959StudioVan Gelder StudioEnglewood Cliffs, New JerseyGenreHard bopLength37:51LabelBlue NoteBLP 4018ProducerAlfred LionWalter Davis Jr. chronology Davis Cup(1960) Night Song(1979) Davis Cup is the debut album by American jazz pianist Walter Davis Jr. recorded on August 2, 1959 and released on Blue Note the following year—Davis's sole release for the label, and...

100 visualisations d'une fonction de distribution empirique, générées à l'aide de JavaScript En statistiques, une fonction de répartition empirique est une fonction de répartition qui attribue la probabilité 1/n à chacun des n nombres dans un échantillon. Soit X1,...,Xn un échantillon de variables iid définies sur un espace de probabilité ( Ω , A , P ) {\displaystyle (\Omega ,{\mathcal {A}},\mathbb {P} )} , à valeurs dans R {\displaystyle \mathbb {R} } , avec pour fonction...

 

 

NS32016 マイクロプロセッサ 320xxまたはns32000はナショナル セミコンダクター (NS) のマイクロプロセッサシリーズである。320xxシリーズにはコプロセッサインターフェイスがあり、FPUやMMUといったコプロセッサを接続することができる。320xxシリーズは Swordfish CPUに受け継がれた。 始まり:32016と32032 このシリーズの最初のチップは16032である(後に32016と改称)。1970年代後�...