How to Copy a Directory Using SCP on Ubuntu
Transferring files securely between machines is a fundamental task in Linux administration. This article provides a straightforward guide on how to copy an entire directory from a local Ubuntu system to a remote server, or vice versa, using the Secure Copy Protocol (SCP) over SSH, including the exact syntax, options, and practical command examples.
The Basic Syntax for Copying a Directory
To copy a directory rather than a single file, you must use the
recursive option, which is represented by the -r flag.
Without this flag, SCP will skip directories and return an error.
The basic syntax for copying a directory is:
scp -r /path/to/source/directory username@remote_host:/path/to/destinationCopying a Local Directory to a Remote Server
To upload an entire directory from your local Ubuntu machine to a remote server, specify the local directory path first, followed by the remote SSH credentials and destination path.
Example:
If you want to copy a local folder named mydata located
in your home directory to a remote server with the IP address
192.168.1.50 under the user ubuntu, use the
following command:
scp -r ~/mydata ubuntu@192.168.1.50:/home/ubuntu/backup/Upon executing this command, you will be prompted to enter the SSH password for the remote user (unless you have SSH keys set up).
Copying a Remote Directory to a Local Machine
To download an entire directory from a remote server to your local Ubuntu system, reverse the order of the source and destination in the syntax.
Example:
To download a directory named project from the remote
server to your local current working directory (represented by a dot
.), use:
scp -r ubuntu@192.168.1.50:/var/www/project .Copying via a Custom SSH Port
By default, SCP connects over the standard SSH port 22. If your
remote server uses a custom SSH port, you must specify it using the
-P (uppercase P) flag. Note that this flag must be placed
before the source path.
Syntax:
scp -P port_number -r /path/to/source/directory username@remote_host:/path/to/destinationExample:
To copy a directory to a server listening on port
2222:
scp -P 2222 -r ~/mydata ubuntu@192.168.1.50:/home/ubuntu/backup/