scp Command in Linux: Secure File Transfer Examples and Syntax
Learn scp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn scp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What scp Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
The scp command in linux is the classic, universally recognized utility for copying files securely across network boundaries. Distributed as an integral component of the OpenSSH suite, scp replaced the historical rcp (remote copy) utility by encapsulating all data transmissions within authenticated, encrypted SSH transport tunnels.
The scp command in Linux (secure copy) transfers files and directories securely between local and remote hosts, or between two remote servers, across an encrypted SSH connection. It uses the same authentication, SSH key infrastructure, and cryptographic transport security as OpenSSH, providing a familiar cp-like syntax for remote file operations.
Whether deploying application configuration files to remote virtual machines, pulling database backups from a production server to an offsite workstation, or staging assets across cloud environments, scp provides an intuitive syntax modeled after the standard POSIX cp command. By leveraging existing SSH key pairs, ssh-agent keyrings, and ~/.ssh/config profiles, scp executes remote file transfers without requiring separate daemon configurations or open FTP ports.
Modern OpenSSH releases (version 9.0 and later) have modernized scp: while retaining the classic command-line flags and argument grammar, modern scp uses the secure SFTP protocol under the hood by default, resolving historical vulnerabilities associated with legacy RCP wire protocol parsing.
What scp Does and When to Use It
Under the hood, scp initiates an encrypted SSH-2 connection over TCP port 22, completing cryptographic host key verification and user authentication (via public key or password). In legacy implementations, scp invoked a remote rcp server process over the SSH channel, which suffered from wildcard expansion ambiguities and quoting vulnerabilities (such as CVE-2019-6111).
In modern OpenSSH (9.0+), scp functions as an SFTP client by default. When you run scp, it requests the sftp subsystem on the remote SSH daemon, transferring files via structured binary SFTP protocol packets. If communicating with an older server that lacks an SFTP subsystem, scp can fall back to the legacy SCP wire protocol using the -O option. Data transferred over the wire is encrypted using modern ciphers like ChaCha20-Poly1305 or AES-GCM.
At the operating system level, scp interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running scp in cloud instances or Kubernetes worker nodes, combining flags such as -P PORT, -i KEY, -r, -p lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.
Availability and Installation Across Linux Distributions
The scp utility is packaged in openssh-client across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether scp is installed and inspect which binary path and version your shell resolves:
type -a scp
scp --version 2>/dev/null || man -f scp
# Illustrative output (reviewed against documentation)
scp is /usr/bin/scp
scp (openssh-client)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y openssh-client
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y openssh-clients
# Arch Linux
sudo pacman -S --noconfirm openssh
# Alpine Linux
sudo apk add --no-cache openssh-client
Command Syntax, Arguments, and Exit Status Codes
scp [OPTIONS] [[user@]host1:]file1 ... [[user@]host2:]file2
The scp syntax follows: scp [OPTIONS] SOURCE DESTINATION. Paths can be local filesystem paths (e.g., /path/to/file) or remote paths formatted as [user@]host:/path/to/destination. If the user@ prefix is omitted, scp defaults to the currently logged-in local username.
Important command options include -P PORT (specifies custom SSH port; note uppercase -P, distinct from ssh's lowercase -p), -i KEYFILE (specifies private identity key), -r (copies directories recursively), -p (preserves modification times, access times, and file modes), -C (enables gzip compression in transit), and -l LIMIT (throttles bandwidth in Kbit/s).
0— Successful execution; all specified files and directories were copied completely.1— Operational error; connection refused, authentication failed, file not found, or permission denied.2— Command-line syntax error or invalid argument supplied.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-P PORT | --port | Specifies the remote SSH port number to connect to (note uppercase -P). |
-i KEY | --identity | Selects the private key file (identity file) used for public key authentication. |
-r | --recursive | Recursively copies entire directory trees and their contents. |
-p | --preserve | Preserves file modification times, access times, and permission modes from the source. |
-C | --compress | Enables transparent compression on the SSH transport stream to accelerate transfers. |
-q | --quiet | Quiet mode; suppresses progress meters, transfer speed statistics, and diagnostic messages. |
-v | --verbose | Enables verbose debugging output, showing SSH connection, cipher negotiation, and authentication. |
-l LIMIT | --limit | Limits transfer bandwidth consumption to LIMIT kilobits per second (Kbit/s). |
-O | --legacy-protocol | Forces scp to use the legacy SCP wire protocol instead of the modern SFTP protocol. |
A common source of confusion is the port option: OpenSSH's ssh command uses lowercase -p for port, whereas scp uses uppercase -P for port (reserving lowercase -p for 'preserve file attributes'). Running scp -p 2222 will mistakenly attempt to preserve attributes on a nonexistent file named '2222'.
For directory synchronization, pairing -r with -p and -C (e.g., scp -rpC ./build/ user@server:/var/www/) preserves accurate timestamps and accelerates transfers over WAN connections by compressing compressible text, HTML, and script assets in flight.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Copy a Local File to a Remote Server
Transfer a configuration file from your local machine to a remote server's home directory.
scp nginx.conf [email protected]:/etc/nginx/
# Illustrative output (reviewed against documentation)
nginx.conf 100% 2450 1.2MB/s 00:00
scp establishes an SSH connection, authenticates, and copies nginx.conf to /etc/nginx/ on the remote server.
2. Copy a Remote File to the Local Machine
Download a remote database backup file to your current local directory.
scp [email protected]:/var/backups/db_backup.sql.gz ./
# Illustrative output (reviewed against documentation)
db_backup.sql.gz 100% 45MB 14.8MB/s 00:03
Reversing the arguments downloads the remote file to the local directory (represented by .).
3. Copy an Entire Directory Recursively Preserving Timestamps
Recursively upload an entire website assets folder while maintaining original modification times and file permissions.
scp -r -p ./assets [email protected]:/var/www/html/
# Illustrative output (reviewed against documentation)
logo.png 100% 120KB 4.2MB/s 00:00
style.css 100% 24KB 1.8MB/s 00:00
app.js 100% 85KB 3.5MB/s 00:00
The -r flag traverses subdirectories, and -p preserves timestamps and permission bits across all transferred files.
4. Transfer Files Using Custom SSH Port and Private Key
Connect to a hardened server running on custom port 2222 using a specific Ed25519 identity key.
scp -P 2222 -i ~/.ssh/deploy_ed25519 release.tar.gz [email protected]:/opt/releases/
# Illustrative output (reviewed against documentation)
release.tar.gz 100% 12MB 11.2MB/s 00:01
The uppercase -P 2222 routes to the non-standard SSH port, and -i supplies the private key for authentication.
5. Copy Files Directly Between Two Remote Servers
Transfer a file directly from server A to server B through your local administrative workstation.
scp [email protected]:/data/report.csv [email protected]:/data/
# Illustrative output (reviewed against documentation)
report.csv 100% 512KB 2.4MB/s 00:00
scp tunnels data between host1 and host2, using your local workstation as the authenticated routing conduit.
6. Limit Bandwidth Consumption to Prevent Network Saturation
Cap transfer speed to 8000 Kbit/s (approx. 1 MB/s) during large file transfers across office networks.
scp -l 8000 disk_image.raw [email protected]:/storage/
# Illustrative output (reviewed against documentation)
disk_image.raw 15% 150MB 980.0KB/s 01:25 ETA
The -l 8000 option limits bandwidth to 8000 Kbit/s, ensuring other network applications are not starved of bandwidth.
Real-World Workflows, Pipelines, and Shell Automation
Automated Deployment Artifact Publishing Pipeline
Integrate scp into a CI/CD build script to securely copy compiled distribution archives to staging servers.
#!/usr/bin/env bash
set -euo pipefail
ARTIFACT="dist/app-v2.0.tar.gz"
REMOTE_USER="deploy"
REMOTE_HOST="staging.example.com"
REMOTE_DIR="/var/www/staging"
KEY_FILE="~/.ssh/ci_deploy_key"
echo "=== Verifying Build Artifact ==="
if [ ! -f "${ARTIFACT}" ]; then
echo "Error: Artifact ${ARTIFACT} does not exist!"
exit 1
fi
echo "=== Uploading Artifact to ${REMOTE_HOST} ==="
scp -i "${KEY_FILE}" -p -C "${ARTIFACT}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/"
echo "=== Extracting Artifact on Remote Server ==="
ssh -i "${KEY_FILE}" "${REMOTE_USER}@${REMOTE_HOST}" "
tar -xzf ${REMOTE_DIR}/app-v2.0.tar.gz -C ${REMOTE_DIR}/
sudo systemctl restart app.service
"
echo "Deployment completed successfully."
# Illustrative output (reviewed against documentation)
=== Verifying Build Artifact ===
=== Uploading Artifact to staging.example.com ===
app-v2.0.tar.gz 100% 18MB 12.4MB/s 00:01
=== Extracting Artifact on Remote Server ===
Deployment completed successfully.
This production pipeline uploads an application archive using scp with compression (-C) and executes remote deployment commands via ssh.
Remote Database Backup Extraction and Local Archive Verification
Securely pull compressed database snapshots from a remote database node to local cold storage, validating transfer integrity.
#!/usr/bin/env bash
set -euo pipefail
REMOTE_SERVER="db.example.com"
REMOTE_FILE="/var/backups/postgres-daily.sql.gz"
LOCAL_DIR="/backups/database"
DATE_STAMP=$(date +%Y%m%d)
TARGET_FILE="${LOCAL_DIR}/postgres-${DATE_STAMP}.sql.gz"
mkdir -p "${LOCAL_DIR}"
echo "=== Downloading Database Backup from ${REMOTE_SERVER} ==="
scp "backup@${REMOTE_SERVER}:${REMOTE_FILE}" "${TARGET_FILE}"
echo "=== Verifying Gzip Archive Integrity ==="
if gzip -t "${TARGET_FILE}"; then
echo "INTEGRITY CHECK PASSED: Backup archive is valid and uncorrupted."
else
echo "ERROR: Backup archive is corrupted!"
exit 1
fi
# Illustrative output (reviewed against documentation)
=== Downloading Database Backup from db.example.com ===
postgres-daily.sql.gz 100% 340MB 24.1MB/s 00:14
=== Verifying Gzip Archive Integrity ===
INTEGRITY CHECK PASSED: Backup archive is valid and uncorrupted.
The script downloads a database backup with scp and immediately runs gzip -t to confirm the archive was not corrupted during transit.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding scp inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
scp unconditionally overwrites pre-existing destination files sharing the same name without confirmation prompts. Transferring a file to a destination where an identically named file exists will permanently replace the target file's contents.
Always configure SSH key pair authentication (using Ed25519 or RSA-4096 keys) and disable root password logins on target servers. When scripting scp in automated environments, use dedicated deploy keys with restricted permissions.
Legacy versions of scp were vulnerable to remote shell injection when handling unescaped wildcards or special characters in filenames (CVE-2019-6111). Ensure your servers run modern OpenSSH (9.0+) where scp defaults to the safe SFTP protocol backend.
GNU/Linux, BSD, and BusyBox Implementation Differences
The scp utility is pre-installed across all Linux distributions, macOS, FreeBSD, and modern Windows 10/11 (via OpenSSH for Windows). Command syntax is uniform across all platforms.
Unlike rsync, scp cannot perform delta transfers (syncing only changed blocks) or resume interrupted transfers. For synchronizing large directory trees or resuming severed downloads, rsync or sftp is preferred over scp.
Troubleshooting Common Errors and Diagnostics
Permission denied (publickey,password)
Root Cause: SSH authentication failed because the public key is not listed in ~/.ssh/authorized_keys on the remote server.
Resolution: Verify user credentials, specify the correct identity key with -i, or copy the key using ssh-copy-id.
scp -i ~/.ssh/id_ed25519 file.txt user@remote-host:/path/
ssh: connect to host ... port 22: Connection refused
Root Cause: The remote SSH daemon is listening on a non-standard port or blocked by a firewall.
Resolution: Specify the correct port using uppercase -P (e.g., -P 2222).
scp -P 2222 file.txt user@remote-host:/path/
scp: /path/file: No such file or directory
Root Cause: The target destination directory does not exist on the remote host (scp does not create parent directories automatically).
Resolution: Create the destination directory on the remote host with ssh user@host 'mkdir -p /path' prior to copying.
ssh user@remote-host "mkdir -p /target/dir"
scp file.txt user@remote-host:/target/dir/
Alternatives, Related Commands, and Related Tutorials
- curl Command in Linux: Transfer Data, Test APIs, and HTTP Requests — Practical syntax, flags, and examples for
curl. - How to Use Linux Screen: Manage Persistent Terminal Sessions — Practical syntax, flags, and examples for
screen. - sftp Command in Linux: Interactive and Automated Secure Transfers — Practical syntax, flags, and examples for
sftp. - How to Transfer Files with Rsync over SSH: Sync, Mirror, and Resume — Practical syntax, flags, and examples for
rsync. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
/var/data/.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides

Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!