The terminal in Linux is a very powerful tool if you know how it works and you know how to use it. A big problem for all beginners is to know the basic commands, a very basic command that we should all know, is the command that allows us to copy files from the Terminal, and it is so simple that it is not necessary to write it down.
Simply copy files
The command we will use is cp. The format that we will be using is the name of the command, followed by a space and the absolute or relative path of the source file to be copied, and another space followed by the full path of the directory where the new file will be copied, including the name that you will have this, which may be different from the source file.
Now in the terminal:
cp /tmp/source-folder/old-file.bin /root/dest-folder/new-file.bin
With this small piece of code, a file is copied to another location, the only drawback is that we have to adjust the permissions after copying it, unless we want it for the same root user.
Using wildcards for simple and recursive copy
Sometimes we need to copy files based on their extension or filename, so using wildcards is best.
If we need to copy files in the first level or recursively from the current folder with the extension ".js".
Simple only the first level:
cp *.js /home/user/dest-folder/
Recursive, all files with the previous extension are copied from the top level and in all subfolders:
cp -R *.js /home/user/dest-folder/
List of useful wildcards:
- *: refers to all content within the directory including other directories, does not select hidden files and folders.
- .: refers to the current folder.
- .*: refers to all files and folders, including hidden ones.
- *.*: refers to all files that use the "name.extension" format.
Copy files and folders recursively
To copy all the content of the source folder to the destination folder we use the
cp -R /tmp/source-folder /root/dest-folder
Copy contents of current folder to another folder recursively
If we are inside a folder and we want to copy all the files recursively to another folder we use the wildcard "." and the parameter
cp -R . /root/folder/
For the above command to work we must place ourselves with
cd in the directory that has the content that we want to copy.
For example “cd /root/folder-with-content/”, and from there execute the command that copies all the contents of the folder but without copying the parent folder.