Share to: share facebook share twitter share wa share telegram print page

Cp (Unix)

cp
Original author(s)AT&T Bell Laboratories
Developer(s)Various open-source and commercial developers
Initial releaseNovember 3, 1971; 52 years ago (1971-11-03)
Written inPlan 9: C
Operating systemUnix, Unix-like, Plan 9, Inferno, KolibriOS
PlatformCross-platform
TypeCommand
Licensecoreutils: GPLv3
Plan 9: MIT License

In computing, cp is a command in various Unix and Unix-like operating systems for copying files and directories. The command has three principal modes of operation, expressed by the types of arguments presented to the program for copying a file to another file, one or more files to a directory, or for copying entire directories to another directory.[1]

The utility further accepts various command line option flags to detail the operations performed. The two major specifications are POSIX cp and GNU cp. GNU cp has many additional options over the POSIX version.[2]

The command is also available in the EFI shell.[3]

History

cp was part of Version 1 Unix.[4] The version of cp bundled in GNU coreutils was written by Torbjorn Granlund, David MacKenzie, and Jim Meyering.[5]

Operating modes

cp has three principal modes of operation. These modes are inferred from the type and count of arguments presented to the program upon invocation.

  • When the program has two arguments of path names to files, the program copies the contents of the first file to the second file, creating the second file if necessary.
  • When the program has one or more arguments of path names of files and following those an argument of a path to a directory, then the program copies each source file to the destination directory, creating any files not already existing.
  • When the program's arguments are the path names to two directories, cp copies all files in the source directory to the destination directory, creating any files or directories needed. This mode of operation requires an additional option flag, typically r, to indicate the recursive copying of directories. If the destination directory already exists, the source is copied into the destination, while a new directory is created if the destination does not exist.

Usage

Copying a file to another file:

cp [-fHip][--] sourcefile targetfile

Copying file(s) to a directory

cp [-fHip] [--] sourcefile... targetdirectory

Copying a directory to a directory (-r or -R must be used)

cp -r|-R [-fHip] [--]  sourcedirectory... targetdirectory

Option flags

  • -f (force) – specifies removal of the target file if it cannot be opened for write operations. The removal precedes any copying performed by the cp command.
  • -H (dereference) – makes the cp command follow symbolic links (symlinks) so that the destination has the target file rather than a symlink to the target.
  • -i (interactive) – prompts with the name of a file to be overwritten. This occurs if the TargetDirectory or TargetFile parameter contains a file with the same name as a file specified in the SourceFile or SourceDirectory parameter. If one enters y (or the locale's equivalent of y), the cp command continues. Any other answer prevents the cp command from overwriting the file.
  • -n (no clobbering) – prevents accidentally overwriting any files
  • -p (preserve) – the -p flag preserves the following characteristics of each source path in the corresponding target: the time of the last data modification and the time of the last access, the ownership (only if it has permissions to do this), and the file permission-bits.
  • -R or -r (recursive) – copy directories recursively

Examples

Creating a copy of a file in the current directory:

cp prog.c prog.bak

This copies prog.c to prog.bak. If the prog.bak file does not already exist, the cp command creates it. If it does exist, the cp command replaces its contents with the contents of the prog.c file.

Copy two files in the current directory into another directory:

cp jones smith /home/nick/clients

This copies the files jones to /home/nick/clients/jones and smith to /home/nick/clients/smith.

Copy a file to a new file and preserve the modification date, time, and access control list associated with the source file:

cp -p smith smith.jr

This copies the smith file to the smith.jr file. Instead of creating the file with the current date and time stamp, the system gives the smith.jr file the same date and time as the smith file. The smith.jr file also inherits the smith file's access control protection.

Copy a directory, including all its files and subdirectories, to another directory:

cp -R /home/nick/clients /home/nick/customers

This copies the directory clients, including all its files, subdirectories, and the files in those subdirectories, to the directory customers/clients. Some Unix systems behave differently in this mode, depending on the termination of directory paths. Using cp -R /home/nick/clients/ /home/nick/customers on a GNU system it behaves as expected; however, on a BSD system, it copies all the contents of the "clients" directory, instead of the directory clients itself. The same happens in both GNU and BSD systems if the path of the source directory ends in . or .. (with or without trailing slash).

The copying of a file to an existing file is performed by opening the existing file in update mode, thereby preserving the files inode, which requires write access and results in the target file retaining the permissions it had originally.

  • cpio – copy an entire directory structure from one place to another
  • tar – create an archive of files
  • link – system call to create a link to a file or directory
  • ln – create a link to a file or directory
  • mv – move a file or directory
  • rm – remove a file or directory
  • unlink – system call to remove a file or directory
  • chmod – change the mode (aka permissions) on a file or directory
  • chown – change ownership on a file or directory
  • chgrp – change group on a file or directory
  • uucp – unix to unix copy
  • scp – secure copy over SSH
  • progress,[6][7] Linux tool to show progress for cp, mv, dd.

See also

References

  1. ^ "Cp(1) - Linux manual page".
  2. ^ "GNU Coreutils: cp invocation". GNU.
  3. ^ "EFI Shells and Scripting". Intel. Retrieved 2013-09-25.
  4. ^ McIlroy, M. D. (1987). A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 (PDF) (Technical report). CSTR. Bell Labs. 139.
  5. ^ "Cp(1): Copy files/Directories - Linux man page".
  6. ^ "Progress(1) - Linux man page".
  7. ^ "Progress - Coreutils Progress Viewer". GitHub. 14 November 2021.

Read other articles:

В Википедии есть статьи о других людях с такой фамилией, см. Муратов; Муратов, Дмитрий. Дмитрий Андреевич Муратов в 2021 году Дата рождения 29 октября 1961(1961-10-29) (62 года) Место рождения Куйбышев, Куйбышевская область, РСФСР, СССР Гражданство  СССР →  Россия Род деятел...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (ديسمبر 2020) تشارلز ماكاي   معلومات شخصية تاريخ الميلاد 29 يونيو 1875  تاريخ الوفاة 3 مايو 1929 (53 سنة)   مواطنة نيوزيلندا  الحياة العملية المهنة سياسي،  ومحامٍ  ت

Coordenadas: 40° 41' 38 N 7° 56' 6 O  Portugal Campo    Freguesia   Símbolos Brasão de armas Localização Localização no município de ViseuLocalização no município de Viseu CampoLocalização de Campo em Portugal Coordenadas 40° 41' 38 N 7° 56' 6 O Região Centro Sub-região Viseu Dão-Lafões Distrito Viseu Município Viseu Código 182306 Administração Tipo Junta de freguesia Características geográficas Área tota...

1999 video gameGuwangeDeveloper(s)CavePublisher(s)Atlus (Arcade)cave (Xbox 360)Designer(s)Kenichi TakanoJunya InoueComposer(s)Masahiro KusunokiPlatform(s)Arcade, i-mode, Yahoo! Mobile, Xbox 360ReleaseArcadeJP: June 24, 1999Mobile PhonesJP: 2003Xbox 360WW: November 10, 2010Genre(s)Manic shooterMode(s)Single-player, 2 player co-opArcade systemCAVE 68000 Guwange (ぐわんげ, Guwange, [ɡɯwaŋɡe]) is a vertical scrolling shooter developed by Cave and published by Atlus in 1999. Gamepl...

Recreational and technical scuba training and certification agency This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) A major contributor to this article appears to have a close connection with its subject. It may require cleanup to comply with Wikipedia's content policies, particularly neutral point of view. Please discuss further on the talk page. (August 2015) (Learn how and when to remov...

This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Subterranean Records – news · newspapers · books · scholar · JSTOR (June 2010) (Learn how and when to remove this template message) Subterranean Records is an independent record label based in San Francisco. Founded by Steve Tupper and a then partner, Michael Fox in 1979,[1] it focused on that city...

هذه المقالة بحاجة لصندوق معلومات. فضلًا ساعد في تحسين هذه المقالة بإضافة صندوق معلومات مخصص إليها. هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يوليو 2020) هذه قائمة بالحوادث المنسوبة إلى مثلث برمودا أو ما يُعرف بم...

Book by Karen Cushman 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: The Midwife's Apprentice – news · newspapers · books · scholar · JSTOR (May 2012) (Learn how and when to remove this template message) The Midwife's Apprentice AuthorKaren CushmanCountryUnited StatesLanguageEnglishGenreChildren's Historica...

The Washington Square Arch Greenwich Village (IPA pronunciation: [ˌgrɛnɪtʃ 'vɪlɪdʒ]) atau the Village adalah daerah pemukiman di Manhattan, New York City. Berbatasan dengan Broadway di timur, Hudson River di barat, Houston Street di selatan, dan 14th Street di utara. Greenwich Village lebih dikenal dengan nama Washington Square atau Empire Ward pada abad ke-19. Karena Greenwich Village dulunya adalah desa yang terpisah dari New York, tata letak jalan-jalannya berbeda dari Commissioners...

Israeli screenwriter This article is an orphan, as no other articles link to it. Please introduce links to this page from related articles; try the Find link tool for suggestions. (January 2021) Savion Einstein Savion Einstein (Hebrew: סביון איינשטיין; born April 27, 1982) is an Israeli screenwriter and producer.[1][2] The daughter of the late sports broadcaster Meir Einstein,[3] she has written numerous advertisements and screenplays. Her work has been r...

Baroness de Mowbray Joan of LancasterBaroness de MowbrayBornc. 1312Norfolk, EnglandDied(1349-07-07)7 July 1349 (aged c. 36-37)Yorkshire, EnglandSpouseJohn de Mowbray, 3rd Baron Mowbray(m. 1326/27; her death 1349)IssueJohn de Mowbray, 4th Baron MowbrayHousePlantagenetFatherHenry, 3rd Earl of LancasterMotherMaud Chaworth English RoyaltyFirst House of LancasterArmorial of Plantagenet Henry, 3rd Earl Henry, 1st Duke Blanche, Baroness Wake of Liddell Maud, Countess of Ulster Joan, Baroness M...

Mister FreezeMister Freeze dalam Batman Annual #1 (Juli 2012).Seni karya Jason Fabok.Informasi publikasiPenerbitDC ComicsPenampilan pertamaSebagai Mister FreezeBatmanInstant Freeze/Rats Like CheeseSebagai Victor Fries:Batman: The Animated SeriesHeart of IcePenampilan komik pertamaSebagai Mr. Zero:Batman #121 (Februari 1959)Sebagai Mister Freeze:Detective Comics #373 (Maret 1968)Dibuat olehSebagai Mr. Zero:Dave Wood (penulis)Sheldon Moldoff (artis)Bob Kane (konsep)Sebagai Victor Fries:Paul Din...

Jean Béliveau in 2009 (rechts) Jean Arthur Béliveau (Trois-Rivières, 31 augustus 1931 – Longueuil, 2 december 2014) was een professionele ijshockeyspeler die 20 seizoenen in de National Hockey League voor de Montreal Canadiens speelde. Als speler won hij de Stanley Cup 10 keer, en als official maakte hij deel uit van zeven championship teams. Jean heeft de meeste Stanley Cup overwinningen door een individu tot op heden. Hij werd opgenomen in de Hockey Hall of Fame in 1972. Hij overleed e...

У этого термина существуют и другие значения, см. Титаник (значения). ТитаникTitanic Жанр Драма Создатель Найджел Стаффорд-Кларк Сценарист Джулиан Феллоуз Режиссёр Джон Джонс В ролях Томас Олдридж[d]Рут Брэдли[d]Драгош Букур[d]Дэвид Колдер[d]Кэмпбелл Мур, СтивенДженна Коулм...

Artikel ini perlu diterjemahkan dari bahasa Inggris ke bahasa Indonesia. Artikel ini ditulis atau diterjemahkan secara buruk dari Wikipedia bahasa Inggris. Jika halaman ini ditujukan untuk komunitas bahasa Inggris, halaman itu harus dikontribusikan ke Wikipedia bahasa Inggris. Lihat daftar bahasa Wikipedia. Artikel yang tidak diterjemahkan dapat dihapus secara cepat sesuai kriteria A2. Jika Anda ingin memeriksa artikel ini, Anda boleh menggunakan mesin penerjemah. Namun ingat, mohon tidak men...

Questa voce sull'argomento Ontario è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Contea di Greydivisione censuariaGrey County LocalizzazioneStato Canada Provincia Ontario AmministrazioneCapoluogoOwen Sound Lingue ufficialiinglese TerritorioCoordinatedel capoluogo44°34′N 80°56′W / 44.566667°N 80.933333°W44.566667; -80.933333 (Contea di Grey)Coordinate: 44°34′N 80°56′W / 44.566667°N 80.933333°...

Rowing club in Shrewsbury, UK Pengwern Boat ClubMottoFloreat SalopiaLocationShrewsbury, ShropshireCoordinates52°42′19.3″N 2°45′47.1″W / 52.705361°N 2.763083°W / 52.705361; -2.763083 (Pengwern Boat Club)Home waterShrewsburyFounded1871MembershipOpenAffiliationsBritish Rowing boat code - PGNHarper Adams University RCWebsitewww.pengwernbc.co.ukEventsShrewsbury RegattaNotable membersLord Kingsland Pengwern Boat Club is the community rowing club in Shrews...

7P

Periodic comet with 6-year orbit 7P/Pons–WinneckeContemporary 1921 illustration of Pons–Winnecke comet[1]DiscoveryDiscovered byJean Louis Pons &Friedrich WinneckeDiscovery dateJune 12, 1819 &March 9, 1858DesignationsAlternative designations1858 E1, 1858 II, 1819 III,1927c, 1933b, 1939c,1945a, 1951c, 1964b,1970b, 1976f, 1983b,1989gOrbital characteristicsEpoch2023-02-25[2]Aphelion5.59 AUPerihelion1.233 AUSemi-major axis3.41 AUEccentricity0.6385Orbital perio...

This article lacks inline citations besides NRIS, a database which provides minimal and sometimes ambiguous information. Please help ensure the accuracy of the information in this article by providing inline citations to additional reliable sources. (August 2023) (Learn how and when to remove this template message) United States historic placeCanal Street SchoolhouseU.S. National Register of Historic Places Show map of VermontShow map of the United StatesLocationCanal St., Brattleboro, Vermon...

Town in Northland Region, New Zealand Place in Northland Region, New ZealandPaihiaWilliams RoadCoordinates: 35°16′56″S 174°5′28″E / 35.28222°S 174.09111°E / -35.28222; 174.09111CountryNew ZealandRegionNorthland RegionDistrictFar North DistrictWardBay of Islands-Whangaroa WardElectoratesNorthlandTe Tai TokerauGovernment • Territorial AuthorityFar North District Council • Regional councilNorthland Regional CouncilArea[1] ...

Kembali kehalaman sebelumnya