To create a script copies files from a local machine to a remote server, you can use the scp
command in a Bash script. Here's how you can write a script that copies a file or multiple files to the remote server:
Step-by-Step Guide
Step 1: Create the Bash Script
- Open Terminal on your Mac.
- Create a new script file (e.g.,
scp_upload.sh
):
nano scp_upload.sh
3. Add the following content to the script. Replace the placeholder values with your remote server details and file paths.
Syntax of scp command:
# scp -r <source_file_or_directory> <username>@<host>:<destination>
Bash script command:
#!/bin/bash
# Server Details
REMOTE_HOST="server.example.com" # Replace with your server's IP address or hostname
REMOTE_USER="your_username" # Replace with your remote server username
REMOTE_PASS="your_password" # Replace with your remote password
REMOTE_DIR="/remote/uploads" # Replace with the remote directory where files will be uploaded
REMOTE_PORT="22" # Replace with your remote port
LOCAL_DIR="/Users/yourusername/Documents/files" # Replace with your local directory containing the files
# SCP Command to Upload Files
sshpass -p "$REMOTE_PASS" scp -P "$REMOTE_PORT" -r "$LOCAL_DIR"/* "$REMOTE_USER"@"$REMOTE_HOST":"$REMOTE_DIR"
# Check for errors
if [ $? -eq 0 ]; then
echo "Files successfully uploaded to $REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR"
else
echo "Error: File upload failed."
fi
Step 2: Make the Script Executable
After saving the script, make it executable by running the following command in Terminal:
chmod +x scp_upload.sh
Step 3: Run the Script
Run the script to upload the files:
./scp_upload.sh
Step 4: Example Usage
Suppose you want to upload files from your local directory /Users/yourusername/Documents/files
to the remote directory /remote/uploads
, you would edit the script like this:
REMOTE_HOST="server.example.com"
REMOTE_USER="your_username"
REMOTE_PASS="your_password"
REMOTE_PORT="22"
REMOTE_DIR="/remote/uploads"
LOCAL_DIR="/Users/yourusername/Documents/files"
After saving the script and making it executable, run:
./scp_upload.sh
This will upload all files in the files
directory to the /remote/uploads
directory on your remote server.