Created
April 8, 2025 04:33
-
-
Save sixtusagbo/031263ad163d4c6098c4d46c117f30fb to your computer and use it in GitHub Desktop.
Bash script for file transfer via SFTP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Copyright © Sixtus Agbo | |
# Bash script for file transfer via SFTP | |
# Usage: ./copy_file.sh <local_file_path> [remote_filename] | |
# Default values | |
REMOTE_USER="foo_remote_user" | |
REMOTE_HOST="foo.server" | |
REMOTE_PATH="/home/foo/bar" | |
SSH_KEY="~/.ssh/foo" | |
function show_usage() { | |
echo "Usage: $0 <local_file_path> [remote_filename]" | |
echo " <local_file_path>: Path to the file you want to upload" | |
echo " [remote_filename]: Optional name for the file at destination (defaults to original filename)" | |
exit 1 | |
} | |
# Check if at least one argument is provided | |
if [ $# -lt 1 ]; then | |
echo "Error: Missing file to transfer!" | |
show_usage | |
fi | |
# Define local file path from argument | |
LOCAL_FILE_PATH="$1" | |
# Check if local file exists | |
if [ ! -f "$LOCAL_FILE_PATH" ]; then | |
echo "Error: Local file '$LOCAL_FILE_PATH' not found!" | |
exit 1 | |
fi | |
# Extract filename from path and determine remote filename | |
ORIGINAL_FILENAME=$(basename "$LOCAL_FILE_PATH") | |
REMOTE_FILENAME="${2:-$ORIGINAL_FILENAME}" | |
echo "Uploading file: $LOCAL_FILE_PATH → $REMOTE_PATH/$REMOTE_FILENAME" | |
# Use SFTP to transfer file (assuming directory already exists!) | |
sftp -i "$SSH_KEY" "$REMOTE_USER@$REMOTE_HOST" <<EOF | |
put "$LOCAL_FILE_PATH" "$REMOTE_PATH/$REMOTE_FILENAME" | |
quit | |
EOF | |
# Verify the file was copied successfully | |
if [ $? -eq 0 ]; then | |
echo "[SUCCESS] File has been uploaded to $REMOTE_HOST:$REMOTE_PATH/$REMOTE_FILENAME" | |
exit 0 | |
else | |
echo "[ERROR] Failed to upload file!" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment