Knowledgebase

How to copy files and folders via SSH

You can copy directories and files through SSH with the cp command. To copy a file use the command followed by the path to the file and then the path to the location where you want to put the copied file. Put a single space between the command and the source path and also between the two paths. The destination path doesn't have to include the file's name if you don't want to change it. For example

cp /home/username/public_html/example.php /home/username/public_html/files

will copy the file example.php which is in the public_html folder, and will create an identical file with the same name in a folder called files (which is a subfolder of the public_html folder). If you want the new file to have a different name just include the name in the destination path (e.g. /home/username/public_html/files/example2.php). You don't have to use the full source path if you change the current working directory to the location of the file that you want to copy. Whether you should use the full destination path depends on where you want to copy the file. If it's in a subfolder of the current working directory, for example, you don't have to use the full destination path. For instance, if we use the above example and we change the current working directory to /home/username/public_html, we can execute with the same result the following command:

cp example.php files

Don't forget when you copy files to include the file extension as well (.php in our case). If the file or a folder in the path has spaces in its name, put quotation marks around it. You can also copy several files with the same command. For example:

cp example.php example2.php /home/username/public_html

will copy the files example.php and example2.php that are in the current working directory and will create identical files with the same names in public_html. If in the destination folder there's a file with the same name as the one you're copying, the file in the destination folder will be replaced.

All these rules also apply when copying directories. The difference is that you have to use the -R option with the command. For example:

cp -R folder folder2

will copy a directory (with everything inside it) called folder that's in the current working directory and will create an identical directory called folder2 in the current working directory. If a directory called folder2 already exists, then folder will be copied inside folder2 (unlike copying files where the destination file is replaced). Of course, you can also use the full source and destination paths.

Was this answer helpful?

 Print this Article

Also Read