The scp (secure copy) command is a powerful tool in Ubuntu for securely transferring files and directories between hosts on a network. This guide will walk you through using scp with practical examples.

What is the scp Command?

The scp command allows you to securely copy files and directories between two locations over an SSH connection. It uses the same authentication and security mechanisms as SSH.

Basic Syntax

The basic syntax for the scp command is:

scp [options] source destination

Copying a File from Local to Remote

To copy a file from your local machine to a remote server:

scp /path/to/local/file user@remote_host:/path/to/remote/directory

Example:

scp ~/Documents/report.txt user@192.168.1.10:/home/user/backup/

Copying a File from Remote to Local

To copy a file from a remote server to your local machine:

scp user@remote_host:/path/to/remote/file /path/to/local/directory

Example:

scp user@192.168.1.10:/home/user/backup/report.txt ~/Documents/

Copying a Directory Recursively

To copy a directory and its contents recursively, use the -r option:

scp -r /path/to/local/directory user@remote_host:/path/to/remote/directory

Example:

scp -r ~/Documents/project user@192.168.1.10:/home/user/backup/

Using the & Symbol to Run Commands in the Background

In Ubuntu, the & symbol at the end of a command runs the command in the background, allowing you to continue using the terminal for other tasks.

Running scp in the Background

To run the scp command in the background, simply append & to the command:

scp /path/to/local/file user@remote_host:/path/to/remote/directory &

Example:

scp ~/Documents/report.txt user@192.168.1.10:/home/user/backup/ &

This will run the scp command in the background, freeing up your terminal for other tasks.

Checking the Progress of Background scp Command

To check the progress of an scp command running in the background, you can use the jobs and fg commands:

  • List background jobs:
jobs

This command will list all jobs running in the background along with their job IDs.

  • Bring the scp command to the foreground:
fg %job_id

Replace job_id with the job ID of your scp command (e.g., fg %1).

Once the job is in the foreground, you can see its progress directly in the terminal.

Combining scp and &

You can use scp with & to copy files or directories in the background, which is especially useful for large transfers:

scp -r ~/Documents/project user@192.168.1.10:/home/user/backup/ &

Conclusion

The scp command is a secure and efficient way to transfer files and directories between hosts. Using the & symbol allows you to run commands in the background, making your workflow more efficient. By mastering these commands, you can streamline your file transfer processes on Ubuntu.