How to Use SCP in Bash Script for Secure File Transfer
Use the
scp command inside a bash script to securely copy files between local and remote systems. The basic syntax is scp source destination, where source or destination can be local paths or remote paths in the format user@host:path.Syntax
The basic syntax of scp is:
- scp: The command to securely copy files.
- source: The file or directory to copy. Can be local or remote.
- destination: Where to copy the file. Can be local or remote.
- Remote paths use the format
user@host:path, whereuseris the remote username,hostis the remote machine, andpathis the file location.
bash
scp [options] source destination
Example
This example script copies a local file file.txt to a remote server's home directory using scp. It shows how to use scp inside a bash script with variables.
bash
#!/bin/bash REMOTE_USER="user" REMOTE_HOST="example.com" REMOTE_PATH="~/" LOCAL_FILE="file.txt" scp "$LOCAL_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH" echo "File copied to $REMOTE_HOST"
Output
File copied to example.com
Common Pitfalls
Common mistakes when using scp in scripts include:
- Not quoting variables, which can cause errors if paths have spaces.
- Forgetting to specify the remote user or host correctly.
- Not handling authentication, which may cause the script to hang waiting for a password.
- Using relative paths without knowing the current directory context.
Always quote variables and consider using SSH keys for passwordless authentication.
bash
# Wrong way (no quotes, may fail if filename has spaces) scp $LOCAL_FILE $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH # Right way (quotes to handle spaces) scp "$LOCAL_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"
Quick Reference
| Option | Description |
|---|---|
| -r | Copy directories recursively |
| -P port | Specify remote SSH port |
| -i identity_file | Use a specific private key file |
| -v | Verbose mode for debugging |
| -q | Quiet mode, no progress output |
Key Takeaways
Use
scp source destination to copy files securely in bash scripts.Always quote variables in
scp commands to handle spaces in paths.Use SSH keys to avoid password prompts in automated scripts.
Remember to specify remote user and host in the format
user@host:path.Use options like
-r for directories and -P for custom ports.