2.3 Copy and move files: cp, mv

Copying a file is possible with the command “cp”. We can copy any file within the same directory as long as the file name of the copy differs from the original, for instance: “cp A B”; in this case we create a copy file called B from A.

cp fileA.txt copy.txt; ls
#copy.txt fileA.txt fileB.txt fileC.txt subdir

Note: Bash will send an error message if we try to make a copy with the same original file name and within the same directory. If we want to keep the same file name for some reason then, instead of providing a different file name, we have to provide another path directory, for example: “cp A subdir/”; in this case we copy file name A to subdir and keep the same original file name. There is no need to provide a file name after the path, unless we want to give a different name; for instance “cp A subdir/B”; we create a copy called B from A in the directory subdir.

Using only “cp” will not allow us to copy a full folder. In order to copy a directory, we have to use the “cp” with the flag “-r”:

cp subdir newdir
#cp: omitting directory ‘subdir’
cp -r subdir newdir; ls newdir
#fileD.txt

Note: the argument -r stands for recursive, meaning that a directory and all its content are copied.

In certain occasion, we have to move files and directories from one location to another. This can be done with the command “mv” follow by the file/directory we want to move as the first argument and the new path location where we will put the new files/directory as a second argument. For example: “mv A subdir/”; this command will move A to subdir folder, but we have to be cautious because if there is a file or directory called A inside subdir, that will be overwritten with the file or directory A that was just moved to subdir.

mv file[C,E].txt subdir; ls subdir
#fileC.txt fileD.txt fileE.txt
mv copy.txt fileE.txt; ls
#fileA.txt fileB.txt fileC.txt fileE.txt subdir

Note: “mv” can also be used to rename files and directories. As we can see from the example above, the file “copy.txt” was renamed to “fileE.txt”. This occurs when we provide a file or directory name that doesn’t exist as a second argument.