How to upload (FTP) files to server in a Bash script

NottDev
2 min readOct 1, 2024

--

To create a script copies files from a local machine to a remote FTP server, you can use the ftp command in a Bash script. Here's how you can write a script that copies a file or multiple files to the remote FTP server:

Step-by-Step Guide

Step 1: Create the Bash Script

  1. Open Terminal on your Mac.
  2. Create a new script file (e.g., ftp_upload.sh):
nano ftp_upload.sh

3. Add the following content to the script. Replace the placeholder values with your FTP server details and file paths.

#!/bin/bash

# Variables
FTP_SERVER="ftp.example.com" # Replace with your FTP server address
FTP_USER="your_username" # Replace with your FTP username
FTP_PASS="your_password" # Replace with your FTP password
LOCAL_DIR="/remote/uploads" # Replace with the local directory path
REMOTE_DIR="/Users/yourusername/Documents/files" # Replace with the remote directory on the server

# FTP upload function
upload_files() {
ftp -inv $FTP_SERVER <<EOF
user $FTP_USER $FTP_PASS
binary # Use binary mode for file transfer
cd $REMOTE_DIR # Change to the remote directory
$(for file in "$LOCAL_DIR"/*; do
echo "put $file" # Upload each file
done)
bye # Exit the FTP session
EOF
}

# Check if the local directory exists
if [ -d "$LOCAL_DIR" ]; then
echo "Uploading files from $LOCAL_DIR to $FTP_SERVER..."
upload_files
echo "Upload complete."
else
echo "Error: Local directory $LOCAL_DIR does not exist."
fi

Step 2: Make the Script Executable

After saving the script, make it executable by running the following command in Terminal:

chmod +x ftp_upload.sh

Step 3: Run the Script

Run the script to upload the files:

./ftp_upload.sh

Step 4: Example Usage

Suppose you want to upload files from your local directory /Users/yourusername/Documents/files to the remote FTP directory /remote/uploads, you would edit the script like this:

FTP_SERVER="ftp.example.com"
FTP_USER="your_username"
FTP_PASS="your_password"
REMOTE_DIR="/remote/uploads"
LOCAL_DIR="/Users/yourusername/Documents/files"

After saving the script and making it executable, run:

./ftp_upload.sh

This will upload all files in the files directory to the /remote/uploads directory on your FTP server.

--

--

NottDev
NottDev

Written by NottDev

Your only limit is your mind.

No responses yet