How cp and mv utilities work in Linux

“cp stands for copy. This command line utility is used to copy files or group of files or directory. It creates an exact image of a file on a disk with different file name. cp command require at least two filenames in its arguments.

cp: we will login as normal user “ntitin” & create certain files/dirs for testing purposes.

Syntax of cp command:

$ cp <src> <dst>

(copy from “src” source to “dst” destination).

1

2

 

Q: what will happen if we will run “rm -rf /” as a “root” user.

Answer: Don’t ever try to run this command as it will destroy everything on your system.

Command:

$ cp k1 test1/

(copy file “k1” to dir “test1”)

Output:

3

Command:

$ cp -i k1 test1/

(copy file “k1” to dir “test1” in interactive mode)

Output:

4

Command:

$ cp test1 test2/

(copy “test1” dir into “test2” dir. it will show errors)

Output:

5

Command:

$ cp -r test1 test2/

(copy recursively “test1” dir into “test2” dir, but the permissions & timestamps will change)

Output:

1

Command:

$ cp -rp test1 test2/

(copy recursively “test1” dir into “test2” dir & preserve permissions)

Output:

6

Command:

$ cp -a test1 test2/

(copy recursively “test1” dir into “test2” dir & preserve permissions. “-a” & “-rp” are equal)

Output:

7

we will test “cp -i” command as a user “root”.

Command:

$ cp -i k1 test1/

(it will ask for confirmation before copying file “k1” into “test1” dir)

why this different behavior with normal & root user?  The reason is “cp -i” is alias to “cp ” for “root” user.

Output:
8

 

Introduction:

“The mv command termed as “Move”, which is a command-line utility to move files or directories from source to target or change the name or rename the files and directories. It supports the moving of a single file, multiple files, and directories. It is very similar to copy command (cp), used for copying and remove files/folders.

The only difference is that move command has features for renaming and moving of files.”

mv: To understand “mv”, we will login as “nitin” user. “mv” is used to rename files as well as cut & paste.

Command:

$ mv k1 k6

(rename “k1” file as “k6”)

Output:

10

Command:

$ mv test3 test4

(rename “test3” dir as “test4”)

Output:

11

Command:

$ mv k2 test1/

(move “k2” file into “test1” dir)

Output:

12

Command:

$ mv -i k3 test1/

(move “k3” file into “test1” dir in interactive mode)

Output:

13

Command:

$ mv k4 test2/k44

(move “k4” file into “test2” dir & renamed the file as “k44”)

Output:

14

Command:

$ mv k5 k6 test3/

(move 2 files “k5” & “k6” into “test3” dir)

Output:

15

Command:

$ mv test1 test4/

(move “test1” dir into “test4” dir)

Output:

16

 

We have seen the usage of the cp and mv utilities in the linuxs.

Answer of the question. We ask you in the blog.

Que: What will happen if we are going to run “rm -rf /” as a “root” user.

Ans: oh! do not run this command. It will destroy everything on your system.

Leave a Reply