Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Linux cp Command with Examples (Copy Files and Folders)

Let's start. We can already make folders and files four ways: touch, cat, nano and vi. On a laptop, the next thing you do with files is copy, cut-paste, rename and delete. Today is copy. On a server there is no mouse and no right-click, so one command does it: cp. We copy down a tree, up a tree and into the current folder. We copy whole folders, many files at once, and with wildcards, every file whose name fits a pattern. Keep your server running and type every command with me.

In this class

  • Setting up the practice tree ravi/one/two
  • cp SOURCE DESTINATION: what to copy, and where to put it
  • Copying down a tree, up a tree (three ways), and into the current folder with .
  • Backup copies, renaming while copying, and the silent overwrite (cp -i)
  • Names with spaces
  • Copying folders with cp -r, and the real error without it
  • What happens when the destination folder already exists
  • Copying sideways, into a sibling folder
  • Why a folder can't be copied into itself
  • Copying many files at once: the last name is the destination
  • The * wildcard: *.txt and my*
  • Making test files fast: file{1..50}.txt and file{a..z}.txt
  • The ? wildcard: ? and ??
  • The file11 to file19 problem, and two right answers
  • Why wildcards need a naming pattern
  • Practice tasks

1. Recap and today's practice tree

Copying needs something to copy. We use the same small tree all class, so build it first.

What you should already know. Making folders and files: Linux File Commands: touch, cat, nano and vi Tutorial. Moving around with paths: Linux Directory Commands: pwd, ls, cd, mkdir for Beginners.

How (from your home folder). Run these three lines:

cd
mkdir -p ravi/one/two
touch my.txt

Check it with tree ravi (or ls -R ravi):

ravi
└── one
    └── two

2 directories, 0 files

So /home/ec2-user holds the folder ravi and the file my.txt; ravi holds one; one holds two.

mkdir and touch take one or many names: mkdir ravi raja rani makes three folders and touch 1.txt 2.txt 3.txt makes three files. What's new with cp is different: it always needs two kinds of names, a source and a destination.

2. cp: source and destination

On a laptop you right-click → Copy, open another folder, right-click → Paste. On a server you say both things in one line.

Ask where the copy will appear before pressing Enter

Write cp report.txt archive in your notebook. Ask first what archive is. If it is an existing directory, the copy becomes archive/report.txt. If the name is absent, the same command creates a file named archive. If it is already a regular file, copying to it can replace its contents. The command does not create a folder from the name alone.

In your practice folder, run test -d archive && ls -ld archive when you mean to copy into a directory. You can create the directory with mkdir -p archive first, then use cp -i report.txt archive/. The trailing slash makes your intent clear. After the copy, look at archive/report.txt and the source. Both should be present.

cp = copy. It needs two parts:

  1. Source: what to copy.
  2. Destination: where to put the copy.
  3. The order is fixed: first the source, then the destination.

For example, this copies the file my.txt into the folder ravi:

cp my.txt ravi
cp needs two things: what to copy, and where toput it cp my.txt SOURCE = what to copy ravi DESTINATION = where to put it cp my.txt ravi ravi is a folder: the copy goes inside it, as ravi/my.txt cp my.txt backup.txt backup.txt is not a folder: you get a second file with the newname cp my.txt you.txt my.mp3 ravi many sources: the LAST name is the destination (a folder) Order matters: first what, then where. mkdir and touch also take manynames: mkdir a b c, touch 1.txt 2.txt 3.txt

Figure 1. cp my.txt ravi: my.txt is the source, ravi is the destination. A folder as destination receives the copy inside it; a new name makes a second file; with many sources the last name is the destination folder.

How cp reads the destination:

  1. If it is an existing folder, the copy goes inside it with the same name: cp my.txt ravi → ravi/my.txt.
  2. If it is not an existing folder, cp makes a file with that name: cp my.txt backup.txt → a second file backup.txt.
  3. The original always stays where it was. Copy never removes anything from the source.

3. Copy down the tree

The most common copy: a file from where you are into a folder below you.

How (you are in /home/ec2-user):

  1. pwd → /home/ec2-user
  2. cp my.txt ravi/one/two
  3. Check: ls ravi/one/two → my.txt

The destination ravi/one/two is a relative path going down: into ravi, then one, then two.

4. Copy up the tree: three ways

Now you are deep inside the tree and want a file to go back up. This is where the paths from the earlier class pay off.

The task. You are in two, and you want my.txt copied up to /home/ec2-user.

Handwritten board: cp my.txt ravi with source and destination written under the two names; a prompt ending in tilde with cp my.txt ravi/one/two; three prompts ending in two with cp my.txt ../../.., cp my.txt /home/ec2-user and cp my.txt ~; on the right a tree home, ec2-user, ravi, one, two with my.txt and arrows going up to ec2-user.

Whiteboard: cp my.txt ravi: source and destination. Then, on the tree home, ec2-user, ravi, one, two: from ec2-user, cp my.txt ravi/one/two copies down; from two, cp my.txt ../../.., cp my.txt /home/ec2-user and cp my.txt ~ all copy up to ec2-user.

How (all three do the same thing):

  1. cd ~/ravi/one/two
  2. Way 1, relative: cp my.txt ../../.. (up to one, up to ravi, up to ec2-user)
  3. Way 2, absolute: cp my.txt /home/ec2-user
  4. Way 3, tilde: cp my.txt ~
  5. Check: ls -l ~/my.txt → the time shows it was just written.

ec2-user already had a my.txt, so each of these replaced it (both are the same empty file here). More on that in section 6.

Count the dots carefully. .. is one level up. From two, one .. is one, two are ravi, three are ec2-user.

Copy down, copy up, bring it here / └─ home └─ ec2-user (my.txt) └─ ravi └─ one └─ two 1. Down: from ec2-user into two ● you are in ec2-user $ cp my.txt ravi/one/two the destination is a path going down 2. Up: from two back to ec2-user ● you are in two $ cp my.txt ../../.. $ cp my.txt /home/ec2-user $ cp my.txt ~ three ways to write the same destination 3. Bring it here: . = this folder ● you are in ec2-user $ cp ravi/one/two/my.txt . the source is far away, the destination is . Check every copy with ls (or tree).

Figure 2. Animation: from ec2-user, cp my.txt ravi/one/two copies down; from two, cp my.txt ../../.., /home/ec2-user or ~ copies up; then cp ravi/one/two/my.txt . brings the file into the current folder. The green dashed box is the new copy.

Ravindra Bagale's Tip

Not sure the copy worked? Look. ls the destination after every cp. A copy you didn't check is a copy you only hope you made.

5. Bring it here: . means this folder

Sometimes the file is far away and you want it where you are standing.

A single dot . means the current directory. It's a destination like any other.

How (you are in /home/ec2-user):

  1. cp ravi/one/two/my.txt .
  2. The source is a path going down; the destination is . (here).

Classroom line

To say "current directory", we write a dot.

If my.txt is already here, this replaces it without asking (see the next section). Here it's the same empty file, so nothing is lost.

Keep the dots apart: . = here, .. = one level up, ~ = home.

6. Backup copies, renaming while copying, and the silent overwrite

Before you edit an important file, keep a copy. If the edit goes wrong, you still have the old version.

A backup in the same folder. Give the copy a new name:

  1. cp 1.txt 2.txt
  2. 2.txt did not exist, so it's created as a copy of 1.txt.

Rename while copying. These four lines all copy my.txt into ravi:

  1. cp my.txt ravi → ravi/my.txt
  2. cp my.txt ravi/ → the same. Tab completion adds the slash for you; it's fine either way.
  3. cp my.txt ravi/my.txt → the same, with the name written out.
  4. cp my.txt ravi/my-backup.txt → the copy gets a new name inside ravi.
Copies in the same folder: backup, overwrite, samefile A backup copy $ cp 1.txt 2.txt 1.txt 2.txt 2.txt did not exist: now it is a copy of 1.txt a new name = rename while copying 2.txt already exists $ cp 1.txt 2.txt no question, no message: old 2.txt is replaced $ cp -i 1.txt 2.txt cp: overwrite '2.txt'? -i asks first: y = replace, n = keep the old file Same name, same place $ cp my.txt my.txt cp: 'my.txt' and 'my.txt' are the same file a copy needs a different name or a different folder Careful: if the destination folder does not exist, cp makes a FILE withthat name. cp my.txt rav (typo) = a file called rav.

Figure 3. cp 1.txt 2.txt makes a backup copy. If 2.txt already exists, cp replaces it without asking, while cp -i asks first. cp my.txt my.txt fails because source and destination are the same file.

Careful: cp overwrites without asking. If 2.txt already exists, cp 1.txt 2.txt replaces it. No question, no message; the old content of 2.txt is gone.

The safe way: cp -i (interactive) asks first:

cp -i 1.txt 2.txt
cp: overwrite '2.txt'?

Type y to replace or n to keep the old file.

Same name, same place. That's not a copy at all:

cp my.txt my.txt
cp: 'my.txt' and 'my.txt' are the same file

A typo trap. If the destination folder doesn't exist, cp doesn't complain. It makes a file with that name. cp my.txt rav (you meant ravi) quietly creates a file called rav.

When 2.txt already exists, cp 1.txt 2.txt overwrites it silently. Use cp -i when the destination might exist. For a backup copy, a plain name such as ravi/my-backup.txt works well.

Ravindra Bagale's Tip

Want a dated backup without typing the date? cp my.txt my-$(date +%F).txt makes a file like my-YYYY-MM-DD.txt with today's date in it. $(date +%F) is replaced by the date before cp runs.

7. Names with spaces

A space separates words on the command line. cp my.txt my folder means three names: my.txt, my and folder.

Put a name with a space in single quotes:

  1. mkdir 'my folder'
  2. cp my.txt 'my folder'
  3. Check: ls 'my folder' → my.txt

Classroom line

If there's a space, put it in single quotes.

Better still: don't use spaces in names. Use my-folder or my_folder.

8. Copying folders: cp -r

A file is one item. A folder is a box with more boxes inside: ravi has one, one has two, two may have files. To copy a folder, cp has to go inside every box at every level.

-r = recursive: again and again, into every folder inside, copying everything. -R (capital) does exactly the same.

Try it without -r first:

cp ravi ravi1
cp: -r not specified; omitting directory 'ravi'

cp refuses, and tells you why. Nothing is copied.

Now with -r:

  1. cp -r ravi ravi1
  2. Check: tree ravi1 → the same one/two inside, with any files.
A file is one item. A folder is a box with boxesinside. File: plain cp $ cp my.txt ravi my.txt → ravi/my.txt one item, nothing inside Folder: cp -r (recursive = go inside every box) $ cp -r ravi ravi1 ravi/ └─ one/ └─ two/ └─ my.txt ravi1/ └─ one/ └─ two/ └─ my.txt $ cp ravi ravi1 cp: -r not specified; omitting directory 'ravi' -R works exactly like -r. cp -r on a single file also works, but it addsnothing: use it for folders.

Figure 4. Left: cp my.txt ravi copies one file. Right: cp -r ravi ravi1 copies the folder ravi with everything inside it. Without -r, cp says -r not specified; omitting directory 'ravi'.

More examples:

  1. mkdir -p one/two/three, then cp -r ravi one/two/three → a copy of ravi, with everything in it, inside three.
  2. cp -r ravi ~/ravi-backup → a backup of the whole folder.

Classroom line

But there's also a trick...

The trick: cp -r my.txt ravi also works on a single file. It adds nothing, though. A file has nothing inside to go into. Keep the habit clean: plain cp for files, cp -r for folders.

Classroom line

Go on, try it yourself.

Without -r you see: cp: -r not specified; omitting directory 'ravi'. cp skips the folder, but still copies any files you named in the same command.

9. When the destination folder already exists

cp -r ravi ravi1 behaves differently the second time you run it. Know this, or you'll end up with folders inside folders.

Choose between another folder and just its contents

Suppose the old folder contains index.html and images/. You want both directly under release/. If you use cp -r old release/ with release/ already present, look for release/old/index.html. If you intend the contents at the top of the release, use cp -r old/. release/ in your practice tree. Then look for release/index.html instead.

The . there identifies the old directory itself as the source of contents. It includes dot files too. Before copying into any real web root, list the old folder with ls -a and pick exactly what you intend to publish. Check the paths on the destination side before putting the release online.

How it behaves:

  1. First run, ravi1 doesn't exist: cp -r ravi ravi1 creates ravi1 as a full copy of ravi.
  2. Second run, ravi1 now exists: cp -r ravi ravi1 puts a new copy inside it, as ravi1/ravi.
  3. Check: ls ravi1 → one ravi

It's the same rule as for files: when the destination is an existing folder, the copy goes inside.

Run cp -r ravi ravi1 twice and look at ravi1 1st run: ravi1 does not exist$ cp -r ravi ravi1ravi1onetwomy.txtravi1 is a full copy of ravi 2nd run: ravi1 already exists$ cp -r ravi ravi1ravi1ravionetwomy.txtthe old copy stays,a new copy goes inside:ravi1/raviravi1 now has:one(old copy)ravi(new copy) Same rule as for files: an existing folder as destinationmeans put it inside. Check with ls ravi1.

Figure 5. The first cp -r ravi ravi1 creates ravi1 as a copy of ravi. The second run, with ravi1 already there, puts a new copy inside it: ravi1/ravi.

If ravi1 already exists, cp -r ravi ravi1 nests the copy as ravi1/ravi. Check with ls ravi1 before and after.

10. Copying sideways: into a sibling folder

Folders next to each other (siblings) are common: dev and prod, old and new.

The setup. /home/ec2-user has two folders, ram and sham. You are in ram, and ram has a file m.txt.

cd
mkdir ram sham
touch ram/m.txt
cd ram

How (two ways):

  1. cp m.txt ../sham → .. goes up to ec2-user, then into sham.
  2. cp m.txt ~/sham → straight from home into sham.
  3. Check: ls ~/sham → m.txt

11. A folder can't be copied into itself

This looks like a normal copy, but it can't work. Understanding why teaches you how cp walks through folders.

The setup. one contains two (mkdir -p one/two). Now copy one into two.

Without -r, the usual message:

cp one one/two
cp: -r not specified; omitting directory 'one'

With -r, think it through:

  1. cp copies one into two.
  2. But two is inside one, so the copy of one must also contain two...
  3. ...which must contain the copy of one again, which contains two again, and so on.
  4. It would never end: an endless loop.

Linux blocks it straight away and copies nothing:

cp -r one one/two
cp: cannot copy a directory, 'one', into itself, 'one/two/one'
Copying a folder into its own child: an endless loop,which Linux blocks $ cp -r one one/two copy one ... ... into two, which is inside one one └─ two the copy would contain itself,again and again: one/two/one one/two/one/two/one one/two/one/two/one/two/one ... cp: cannot copy a directory, 'one', into itself,'one/two/one' cp refuses and copies nothing. Without -r you only get the omittingdirectory message. $ cp -r one ~/backup works: the destination is outside the source Rule: the destination must not be inside the source.

Figure 6. cp -r one one/two would put one inside its own child two, so the copy would contain itself again and again. cp blocks it with cannot copy a directory into itself. Copying one to a folder outside it, such as ~/backup, works.

Rule: the destination must not be inside the source. cp -r one ~/backup is fine.

Copying a folder into itself would be an endless loop, which Linux blocks. GNU cp spots it before it starts and stops at once with cannot copy a directory, 'one', into itself, 'one/two/one'.

12. Copying many files at once

Copying ten files with ten commands is slow. One cp can take many sources.

  1. You can name as many sources as you like.
  2. The last name is always the destination.
  3. With more than one source, the destination must be an existing folder.

How (you are in /home/ec2-user). Make the files, then copy all three in one go:

touch you.txt my.mp3
cp my.txt you.txt my.mp3 ravi

Check: ls ravi → my.mp3, my.txt and you.txt are now there, next to one and anything you copied earlier.

Handwritten board: a prompt ending in tilde with ls, the names my.txt, you.txt, ravi and my.mp3 underneath; below it cp my.txt you.txt my.mp3 ravi with my.mp3 and ravi underlined and the word destination written under ravi.

Whiteboard: ls shows my.txt, you.txt, ravi and my.mp3. cp my.txt you.txt my.mp3 ravi copies all three files, and the last name, ravi, is marked as the destination.

If the last name isn't a folder, cp stops:

cp my.txt you.txt my.mp3
cp: target 'my.mp3' is not a directory

Newer coreutils versions word it cp: target 'my.mp3': Not a directory; the meaning is the same.

Classroom line

You only got the feeling it worked; in reality it didn't happen.

That's why you always check with ls.

13. The * wildcard

Typing every file name doesn't scale. Usually the names share something: all end in .txt, all start with my. Wildcards let you describe the pattern instead of listing names.

Preview the names, then copy the exact same set

Before cp starts, the shell expands an unquoted wildcard into the matching names in the current folder. Try printf '%s ' *.txt in your practice folder. Read one returned name per line. A matching directory ending in .txt can appear too. If Bash prints a literal *.txt under its usual default settings, no files matched. Check pwd and the case of the file extensions.

Now compare it with printf '%s ' '*.txt'. Single quotes protect the star and the command sees it as text. Use quotes when you mean a literal pattern. Leave the wildcard unquoted when you want the shell to select files, and use the same unquoted pattern for the copy after you have checked the list.

* matches any characters, any number of them, even none.

  1. cp *.txt ravi → every name that ends in .txt.
  2. cp my* ravi → every name that starts with my (my.txt, my.mp3, my.mp4...).
Handwritten board: a prompt ending in tilde with ls; underneath my.txt, you.txt, ravi, my.mp3, 1.txt, 2.txt, dots, 50.txt, then my.logs and my.mp4; below that cp *.txt ravi and cp my* ravi.

Whiteboard: ls shows my.txt, you.txt, ravi, my.mp3, 1.txt, 2.txt up to 50.txt, my.logs and my.mp4. Then cp *.txt ravi copies every name ending in .txt, and cp my* ravi every name starting with my.

Wildcards pick names that fit a pattern Files in the folder: $ cp *.txt ravi→ cp my.txt you.txt 1.txt 2.txt file1.txt filea.txtfile11.txt fileaa.txt ravi* = any characters, any number (even none) $ cp my* ravi→ cp my.txt my.mp3 my.mp4 ravistarts with my, anything after $ cp file?.txt ravi→ cp file1.txt filea.txt ravi? = exactly one character $ cp file??.txt ravi→ cp file11.txt fileaa.txt ravi?? = exactly two characters $ cp Ram* ravi→ cp Ram Ramayan raviRam itself also matches: * can be empty my.txt you.txt my.mp3 my.mp4 1.txt 2.txt file1.txt filea.txt file11.txt fileaa.txt Ram Ramayan Green = matches. The shell swaps the pattern for the matchingnames before cp even starts.

Figure 7. Animation over twelve names: *.txt picks every name ending in .txt, my* picks names starting with my, file?.txt picks file1.txt and filea.txt, file??.txt picks file11.txt and fileaa.txt, and Ram* picks Ram and Ramayan.

Who does the matching? The shell, not cp. Before cp starts, bash swaps *.txt for the matching names. Preview it with echo, which creates and copies nothing:

  1. echo *.txt → for example 1.txt 2.txt my.txt you.txt
  2. echo my* → for example my.mp3 my.txt

When nothing matches, bash passes the pattern as it is, and cp looks for a file literally called *.pdf:

cp *.pdf ravi
cp: cannot stat '*.pdf': No such file or directory

When a folder matches, for example a folder my.logs, plain cp my* ravi copies the files and skips the folder with cp: -r not specified; omitting directory 'my.logs'.

Extensions like .txt are for people and programs; to Linux they're just part of the name. That's exactly why *.txt works: it's matching letters, nothing more.

14. Making test files fast: brace ranges

To practise wildcards you need lots of files. Nobody types fifty touch commands.

Braces with two dots make a range:

  1. touch file{1..50}.txt → file1.txt to file50.txt (50 files)
  2. touch file{a..z}.txt → filea.txt to filez.txt (26 files)
  3. touch file{10..20}.txt → file10.txt to file20.txt (11 files; any start and end work)
  4. touch file{01..12}.txt → file01.txt to file12.txt (a leading zero pads every number)

Preview first with echo: echo file{1..5}.txt → file1.txt file2.txt file3.txt file4.txt file5.txt

This is the same brace shortcut as {Ram,Laxman} from the files chapter, but with a range instead of a list.

15. The ? wildcard: exactly one character

* is greedy: it matches anything of any length. Sometimes you need "exactly one character here".

? matches exactly one character. ?? matches exactly two.

Take four files, file1.txt, filea.txt, file11.txt and fileaa.txt:

  1. cp file?.txt ravi → file1.txt and filea.txt (one character after file)
  2. cp file??.txt ravi → file11.txt and fileaa.txt (two characters)
Handwritten board: file1.txt, filea.txt, file11.txt and file aa.txt across the top; cp file?.txt ravi and cp file??.txt ravi on the left, each question mark drawn like a curly hook; on the right touch file{a..z}.txt with filea.txt and fileb.txt written above it.

Whiteboard: Four files: file1.txt, filea.txt, file11.txt and fileaa.txt. cp file?.txt ravi copies the ones with one character after file, cp file??.txt ravi the ones with two. On the right, touch file{a..z}.txt makes filea.txt, fileb.txt and so on.

Count check. In a folder with file{1..50}.txt, file{a..z}.txt and fileaa.txt:

  1. file?.txt → 35 names (file1 to file9, plus filea to filez)
  2. file??.txt → 42 names (file10 to file50, plus fileaa)

16. The file11 to file19 problem

This task shows how easily a wildcard grabs more than you meant. On a real server the same mistake copies or deletes the wrong log files, so learn to check what a pattern matches before you use it.

The task. The folder has file1.txt to file50.txt. Copy only file11.txt to file19.txt into ravi.

The tempting answer is wrong: cp file1* ravi. * can be empty, so file1* matches:

  1. file1.txt itself (nothing after the 1)
  2. file10.txt (one more digit, but it's 10, not 11 to 19)
  3. file11.txt to file19.txt
  4. and file100.txt, if it existed

The same trap with words: Ram* matches Ram, Rama and Ramayan.

Right answer 1: a brace range. It works for existing files too, because the shell writes out the names before cp starts:

cp file{11..19}.txt ravi

Right answer 2: brackets. [1-9] means one character from 1 to 9:

cp file1[1-9].txt ravi
Task: copy only file11.txt to file19.txt into ravi $ cp file1* ravi wrong: also takes file1.txt and file10.txt ✓ file1 file10 file11 … file19 ✗ file2 … file9 file20 $ cp file{11..19}.txt ravi right: braces write out the nine names ✓ file11 … file19 $ cp file1[1-9].txt ravi right: [1-9] = one character from 1 to 9 ✓ file11 … file19 Boxes = file1.txt ... file20.txt. Same trap with names: Ram* picks Ram, Ramaand Ramayan. Braces make names even if the file is missing (cp: cannot stat ... No suchfile); wildcards only pick names that exist.

Figure 8. Twenty boxes, file1 to file20. cp file1* ravi wrongly also takes file1 and file10. cp file{11..19}.txt ravi and cp file1[1-9].txt ravi take exactly file11 to file19.

The difference between the two:

  1. Braces make names, whether the files exist or not. If one is missing, cp prints cp: cannot stat 'file19.txt': No such file or directory for it and copies the rest.
  2. Wildcards and brackets only pick names that exist. A missing file is simply not picked.

Both answers for file11 to file19 are above: cp file{11..19}.txt ravi and cp file1[1-9].txt ravi. Braces work in cp too, not only when creating files. Don't use file1* here: it also matches file1.txt itself, because * can match nothing.

17. Wildcards need a naming pattern

A wildcard can only describe what the names have in common. If the names have nothing in common, there's no pattern to write.

Classroom line

Wildcards work only where the names follow a pattern.

In practice:

  1. report-jan.txt, report-feb.txt, report-mar.txt → report-*.txt picks them all.
  2. a.txt, notes, final_v2.doc → no useful pattern; name them one by one.
  3. log01 to log30 (zero-padded) → log0? picks 01 to 09, log1? picks 10 to 19. Without the zero, log1* also catches log1.

Ravindra Bagale's Tip

Name things for the wildcard you'll need later: same prefix, same extension, numbers padded with zeros. On a real server this is what lets you copy or clean up "all of last month's logs" in one line. More copy, move and remove commands: 3.3 Working with files and directories.

18. Hands-on lab: copy files and folders with cp

Copying is how you take backups before an edit and move work between folders. This lab covers every case from this chapter: down, up, here, overwrite, folders and wildcards.

  1. Set up the tree and a file
    • Command: cd && mkdir -p ravi/one/two && touch my.txt
    • You should see: Nothing.
    • Check: ls shows my.txt ravi.
    • Why: Every copy needs a source and a destination. This gives you both, in a known place.
  2. Copy down the tree
    • Command: cp my.txt ravi/one/two
    • You should see: Nothing.
    • Check: ls ravi/one/two → my.txt, and ls still shows my.txt here.
    • Why: cp SOURCE DESTINATION: what, then where. A folder as destination means the copy goes inside it with the same name. The source always stays.
  3. Copy up, using ..
    • Command: cd ravi/one/two && cp my.txt ../../..
    • You should see: Nothing.
    • Check: ls ~ still shows one my.txt (it was replaced).
    • Why: Three .. climb from two to /home/ec2-user. ~ or /home/ec2-user as destination would do the same.
  4. Bring a file here with .
    • Command: cd ~/ravi && cp one/two/my.txt .
    • You should see: Nothing.
    • Check: ls → my.txt one
    • Why: . is the folder you stand in. It saves typing the full path of where you are.
  5. Take a backup with a new name
    • Command: cp my.txt my.txt.bak
    • You should see: Nothing.
    • Check: ls → my.txt my.txt.bak one
    • Why: Before you edit a file, keep a copy. If the edit goes wrong, cp my.txt.bak my.txt brings the old version back.
  6. See the overwrite warning
    • Command: cp -i my.txt my.txt.bak
    • You should see: cp: overwrite 'my.txt.bak'?
    • Check: Type n and press Enter. The backup is untouched.
    • Why: Plain cp replaces an existing file silently. -i (interactive) asks first, so use it when the destination might hold something you need.
  7. Try to copy a folder without -r
    • Command: cd && cp ravi ravi1
    • You should see: cp: -r not specified; omitting directory 'ravi'
    • Check: ls shows no ravi1.
    • Why: A folder is a box of boxes. Without -r, cp refuses rather than copy an empty shell.
  8. Copy the folder with -r
    • Command: cp -r ravi ravi1
    • You should see: Nothing.
    • Check: ls ravi1/one/two → my.txt
    • Why: -r (recursive) walks into every folder at every level and copies everything it finds.
  9. Run the same copy again
    • Command: cp -r ravi ravi1
    • You should see: Nothing.
    • Check: ls ravi1 → my.txt my.txt.bak one ravi. A new ravi sits inside ravi1.
    • Why: This time ravi1 already exists, so it is treated as a folder to copy into. Check whether the destination exists before running cp -r.
  10. Make 50 test files
    • Command: mkdir -p wild && cd wild && touch file{1..50}.txt
    • You should see: Nothing.
    • Check: ls | wc -l → 50
    • Why: A brace range writes the 50 names for you. wc -l counts the lines ls prints, one per file.
  11. See what file1* really matches
    • Command: echo file1*
    • You should see: file1.txt file10.txt file11.txt ... file19.txt
    • Check: 11 names, not the 9 you might expect.
    • Why: echo shows what the shell expands a pattern into, without running anything risky. * can match nothing, so file1.txt and file10.txt sneak in.
  12. Copy exactly file11 to file19
    • Command: mkdir ../pick && cp file1[1-9].txt ../pick
    • You should see: Nothing.
    • Check: ls ../pick | wc -l → 9
    • Why: [1-9] matches exactly one character from 1 to 9, so only the two-digit names starting with 1 are picked.
  13. Use ? for one character
    • Command: echo file?.txt
    • You should see: file1.txt file2.txt ... file9.txt
    • Check: 9 names; no two-digit ones.
    • Why: ? is exactly one character, never zero, never two. It is the tool when the length of the changing part is fixed.
  14. Clean up and stop
    • Command: cd && rm -r wild pick ravi1
    • You should see: Nothing.
    • Check: ls → my.txt ravi. Then stop the instance.
    • Why: Keep ravi and my.txt; the next chapter (mv and rm) uses them. Stopping saves free-tier hours.

19. Practice

Try at home

Task 1: up, down, here

  1. Build ravi/one/two and my.txt in ~ (section 1).
  2. Copy my.txt into two from ~.
  3. cd into two and copy it back up three ways: ../../.., /home/ec2-user, ~.
  4. Go home and bring ravi/one/two/my.txt here with ..

Task 2: backups

  1. echo old > 2.txt, echo new > 1.txt, then cp 1.txt 2.txt. Read 2.txt. What happened to old?
  2. Repeat with cp -i and answer n.
  3. Make ravi/my-backup.txt from my.txt in one command.

Task 3: folders

  1. cp ravi ravi1. Read the error.
  2. cp -r ravi ravi1, then run it again. Explain what ls ravi1 shows.
  3. Try cp -r one one/two and read the message.

Task 4: wildcards

  1. In a new folder w: touch file{1..50}.txt file{a..z}.txt fileaa.txt
  2. Predict, then check with echo: file?.txt, file??.txt, file1*, file*a.txt.
  3. Copy only file11.txt to file19.txt into a folder r, both ways.
  4. cp file?.txt r copies more than file1.txt to file9.txt in this folder. Why? Copy only those nine with brackets.

If you get an error, read it slowly: cp nearly always says exactly what's wrong. When you finish, stop the instance from the console.

Classroom line

If you get an error, ask me.

Common errors and fixes

Error / symptomFix
cp: -r not specified; omitting directoryAdd -r (or -R) to copy folders.
cannot copy a directory into itselfPick a destination outside the source tree.
Overwrote a file by mistakeRestore from .bak if you made one. Next time use cp -i.
Wildcard matched nothing usefulQuote patterns carefully; check with echo file* before cp.
Copied into the wrong folderpwd and ls destination first; trailing names matter.

FAQ

Q. Does cp remove the original?

No. Removing is rm / moving is mv (next lessons).

Q. * vs ?

* any string (including empty). ? exactly one character.

Q. Why -i?

Interactive: asks before overwriting. Safer while learning.

Q. Destination exists as a directory?

Source is placed inside that directory (same as many desktop “copy into folder” actions).

Recap

In short

  1. cp SOURCE DESTINATION: what, then where. The source is never removed.
  2. A folder as destination → the copy goes inside. Any other name → a file with that name.
  3. Down: cp my.txt ravi/one/two. Up from two: ../../.., /home/ec2-user or ~. Here: .
  4. cp 1.txt 2.txt makes a backup, and overwrites 2.txt silently if it exists. cp -i asks first.
  5. cp my.txt my.txt → are the same file. A typo in a folder name makes a file instead.
  6. Quote names with spaces: 'my folder'. Better, avoid spaces.
  7. Folders need cp -r (or -R). Without it: -r not specified; omitting directory.
  8. cp -r ravi ravi1 again, when ravi1 exists → ravi1/ravi.
  9. A folder can't go into its own child: cannot copy a directory ... into itself. An endless loop, which Linux blocks.
  10. Many sources: the last name is the destination, and it must be a folder.
  11. * = any characters (even none); ? = exactly one. The shell expands them; preview with echo.
  12. touch file{1..50}.txt, file{a..z}.txt: brace ranges make names fast.
  13. Only file11 to file19: cp file{11..19}.txt ravi or cp file1[1-9].txt ravi. Not file1*.
  14. Wildcards need a naming pattern: plan your names.

Samjla ka? Ghari sagle tasks karun bagha ani pratyek cp nantar ls ne check kara.


Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. The folder and file names (ravi, one, two, ram, sham, my.txt, file1.txt and the rest) are examples for learning. Command outputs and error messages were checked with GNU bash and coreutils, the same tools Amazon Linux 2023 uses.

Worked example: verify which files a backup includes

Suppose your small website has an index.html and a hidden .settings file. You copy it before editing, but the restored site behaves differently. First check which files the original command actually selected.

mkdir -p "$HOME/copy-practice/source" "$HOME/copy-practice/backup"
cd "$HOME/copy-practice"
printf '%s
' 'Home page placeholder' > source/index.html
printf '%s
' 'Sample setting' > source/.settings
printf '%s
' source/*
cp -a source/. backup/
ls -la backup
cmp source/.settings backup/.settings

The shell expands source/* before cp runs. In a default Bash configuration it skips a name beginning with a dot. Copying source/. to an existing destination includes the directory contents, including dotfiles. Here cmp should finish silently with exit status 0. On a real webroot, first classify private files and store required backups outside the public directory.

Interview question: why write source/. instead of source?

For an existing destination directory, copying source creates a nested backup/source directory. The source/. form copies the source contents into backup. Always check the result with ls -la.

Reference 1 · Reference 2

Practise this chapter

Interview questions and answers

How would you copy a release folder so that index.html lands directly inside a new document root?

First make sure the intended destination directory exists. In the exercise, use cp -r source/. target/ to copy the directory contents into target. Check target/index.html and any included dotfiles before publishing.

Where is *.txt expanded in cp *.txt archive/, and why is this useful to know?

The shell expands it in the current directory before cp starts. Print the same unquoted pattern first to catch unexpected names and directories. Single quotes would hand cp a literal filename containing the star.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. The folder release already exists. You run cp -r old release/. Where should you look for an index.html from inside old?

Answer and explanation

B. release/old/index.html

Copying the named source directory into an existing directory keeps the old directory name. For just its contents, use old/. as the source in the lab.

2. What does Bash pass as the source argument in cp '*.txt' archive/?

Answer and explanation

C. The literal text *.txt

Single quotes protect the star from shell expansion. Without quotes the shell can select names before starting cp.

3. You run cp notes.txt archive and archive does not exist. What does a successful command create?

Answer and explanation

A. A regular file named archive containing the same data

With a single regular-file source and a nonexistent destination, cp uses the destination as the new file name. Create a directory first when you want a copy inside one.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Singapore Freight is a logistics business in Singapore. Wei Ling Tan looks after its IT and cloud work. They count money in SGD and run their AWS resources in the ap-southeast-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 12

Easy Find the database endpoint

Your app connects using the endpoint name, not an IP.

Describe DB instance sgfreight-db.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Copy a folder with everything inside

A plain copy skips folders. You need the recursive option to copy a whole tree.

Copy the folder site to a new folder named site-backup (both in the current folder).

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Read a config file

Reading a file on the screen is the quickest way to check its settings.

Print the whole file /etc/sgfreight/app.conf on the screen.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy List all files with details

Hidden files (like .env) and file sizes or owners only show with the right options.

Show a long listing of every file, including hidden ones, in /var/www/sgfreight.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Create an empty file

Some apps need a file to exist before they can write to it.

Create an empty file named orders-sgd.csv in the current folder.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Biggest orders first

Querying the database is daily work after you set up RDS.

Show order id and amount, biggest amount first.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Easy Filter customers by city

Querying the database is daily work after you set up RDS.

List the names of customers in Pune.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Remove small orders

Querying the database is daily work after you set up RDS.

Delete orders with amount below 200.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Orders with customer names

Querying the database is daily work after you set up RDS.

Show each customer name with each order amount.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Total sales

Querying the database is daily work after you set up RDS.

Show the total of all order amounts as one number.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Hard Sales per customer

Querying the database is daily work after you set up RDS.

Show customer_id and total amount per customer, only where total is above 1000.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Hard Customers with no orders

Querying the database is daily work after you set up RDS.

List names of customers who have never ordered.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: cp: copy files. Before editing a config, you need a backup copy. cp SOURCE DESTINATION copies what (source) to where (destination). Use -i to be asked before an overwrite; . means the current folder. Backup:
Revision card: cp: copy files · Download PNG
Revision card: Copy folders with cp -r. cp alone refuses folders: "omitting directory". -r (recursive) copies the folder and everything inside it. If the destination exists, the folder goes INSIDE it. Copy a site:
Revision card: Copy folders with cp -r · Download PNG
Revision card: Wildcards * and ?. Typing 50 file names by hand is slow. * matches any number of characters. ? matches exactly one. Use a naming pattern so one wildcard picks the right files. *.txt = all txt; file?.txt = file1 to file9 only.
Revision card: Wildcards * and ? · Download PNG
Revision card: Make test files with {1..50}. Practising wildcards needs many files fast. Brace expansion makes the shell write a list for you. Put a range in braces after touch. 50 files in one go:
Revision card: Make test files with {1..50} · Download PNG
Comparison: * wildcard vs ? wildcard. * wildcard: Matches any number of characters, even none. ? wildcard: Matches exactly one character.
Comparison: * wildcard vs ? wildcard · Download PNG
Interview card: Why does cp fail on a folder, and how do you fix it?. cp copies files only; folders need -r (recursive). Without -r it says "omitting directory". Fix:
Interview card: Why does cp fail on a folder, and how do you fix it? · Download PNG
Interview card: How do you stop cp from silently overwriting files?. Use -i to be asked, or -n to never overwrite. Plain cp replaces the destination without warning. Ask first:
Interview card: How do you stop cp from silently overwriting files? · Download PNG
Interview card: How do you copy only file11 to file19 with a wildcard?. Use file1? : it matches file1 followed by exactly one character. file1* would also match file1 and file100. Command:
Interview card: How do you copy only file11 to file19 with a wildcard? · Download PNG

More cards: Ravi Sir's Cards.