How to Use rsync to Transfer Files to a Server and Set Ownership and Permissions Using sudo

Abstract: Resolves permission denied errors by using sudo rsync with --chown to correctly set file ownership and permissions on the remote server.

Created: 2026-08-11 by
Use rsync with the -avz flags to archive, compress, and transfer files securely via SSH. To set ownership and permissions on the remote server, you must execute the command with sudo privileges because standard users cannot change file attributes for other accounts. This approach ensures that your deployed assets retain their intended security posture immediately upon arrival.

Prerequisites and User Configuration

Before initiating any file synchronization process, ensure that your local machine can authenticate with the target Ubuntu server without interactive password prompts if you plan to automate this workflow. While not strictly required for a one-time manual transfer, configuring SSH keys significantly improves efficiency. You should also verify that the destination directory exists and is accessible. If the target folder resides in a protected system path like /var/www, only the root user or users with specific sudo rights can modify its metadata. It is critical to understand that rsync itself does not possess magic powers to bypass operating system security models. When you invoke sudo rsync, the remote side runs the daemon as root. This allows it to chown (change owner) and chmod (change mode) files regardless of who initiated the connection. However, this also means that any errors during transfer might leave partial files owned by root, which can complicate subsequent updates. Always test with a small subset of data first to confirm that the permission mapping behaves as expected. For more details on managing sudo access and avoiding common pitfalls, see How did this usage of chmod break sudo access?. Understanding these underlying mechanisms helps prevent accidental lockouts when automating deployment scripts.

Constructing the Secure Command

The core syntax involves specifying the source path, the remote destination, and the necessary flags. The most common invocation looks like this:
sudo rsync -avz --chown=user:group /local/path/ user@remote:/remote/path/
Let's break down the components. The -a flag stands for archive mode, which recursively copies directories while preserving symbolic links, permissions, timestamps, group, and owner. The -v flag enables verbose output, allowing you to monitor progress and verify exactly which files are being transferred. The -z flag compresses data during transfer, reducing bandwidth usage, which is particularly useful for large text-based assets. The --chown option is the key to solving the ownership problem. It explicitly sets the user and group IDs on the receiving end. Without this flag, files might default to the user account used for the SSH connection, leading to "Permission denied" errors when trying to write to those files later. For example, if you are deploying a web application, you typically want the files owned by www-data or a dedicated deployment user rather than your personal admin account. If you need to adjust permissions specifically, such as ensuring executable scripts remain executable, you can add --chmod=ugo=rwX. This sets read/write for users and groups, and execute only for directories and existing executable files. Be cautious with broad permission changes, as overly permissive settings can expose sensitive configuration files to unauthorized users. For related issues regarding permission denial in web contexts, review PHP file_put_contents: Failed to open stream: Permission denied.

Handling Existing Files and Updates

One of the greatest strengths of rsync is its ability to perform incremental updates. By default, it compares modification times and file sizes. If a file has changed since the last sync, it transfers only the differences. This makes subsequent deployments much faster than full uploads. However, this behavior can sometimes lead to stale files remaining on the server if they were deleted locally but still exist remotely. To address this, you can use the --delete flag. This instructs rsync to remove files from the destination that no longer exist in the source. Use this with extreme caution, as it effectively mirrors the source directory structure exactly. A typo in your source path could result in the deletion of important data on the remote server. It is often safer to run the command once without --delete to inspect the log output before committing to a destructive sync. When dealing with previous executions, understanding how rsync handles updates is vital to maintaining system integrity. See How to Make rsync Update Files Transferred in Previous Executions for deeper insights into synchronization logic.

Troubleshooting Common Errors

Even with correct syntax, you may encounter permission-related hurdles. If you receive a "Permission denied" error during the transfer phase, it usually indicates that the SSH user lacks write access to the target directory, not that sudo failed. Remember, sudo applies to the command execution, but the SSH authentication happens beforehand. Ensure your SSH key has the necessary privileges to connect to the remote host. Another frequent issue arises when trying to preserve ownership. If you do not use sudo on the remote command, rsync will silently fail to set the correct owner, leaving files with incorrect permissions. This can cause applications to crash or refuse to start. Always verify the ownership after the transfer completes using ls -l on the remote server. If you face persistent permission blocks in specific subdirectories, such as www, consult Fixing rsync Permission Denied Error in www Subfolder for targeted solutions. Additionally, if you are working within containerized environments, check for volume mount restrictions that might override local permission settings, as discussed in Troubleshooting Docker Container Unable to Write to Removable Drive.

Frequently Asked Questions

Can I use rsync without sudo if I own the files?

Yes, if you are transferring files to a directory where your user account already has write and modify permissions, you do not need sudo. In this case, the files will retain their original ownership and permissions from the source machine automatically.

What happens if the remote server is unreachable during transfer?

Rsync will pause and retry based on network conditions. If the connection drops completely, you can resume the transfer from where it left off by running the same command again, provided you do not delete the partially transferred files.

Does rsync encrypt the data during transfer?

No, rsync itself does not encrypt data. However, when used over SSH (which is the standard method), all data is encrypted transitively. This ensures that credentials and file contents cannot be intercepted by third parties on the network.

How do I exclude specific files like .git or node_modules?

You can use the --exclude flag followed by the pattern, such as --exclude='.git' or --exclude='node_modules/'. You can include multiple excludes in a single command to tailor the transfer to your needs.

Is it safe to use --delete on production servers?

It is generally risky on production environments unless you have verified backups. Accidental deletions can take down websites or remove critical configurations. Always test the command with --dry-run first to preview what would be deleted.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More