Can't scp files with long/weird filenames: Invalid argument

Abstract: Resolve scp Invalid argument errors for long or special-character filenames by bundling files into a tar archive before transfer.

Created: 2026-07-27 by

Scp fails with an "Invalid argument" error for long or special-character filenames primarily because the destination filesystem (often FAT32/vFAT) rejects names exceeding 255 characters or containing invalid symbols. The most reliable solution is to compress files into a tar archive on the source, transfer the single archive via scp, and extract it at the destination. This bypasses filename length restrictions entirely.

Understanding the Root Cause

The "Invalid argument" (EINVAL) error in scp is rarely a network issue. It is almost always a filesystem constraint violation. When you transfer a file, scp creates the file on the remote host using the exact same name. If that name violates the rules of the target filesystem, the operating kernel rejects the system call. Common culprits include:
  • FAT32/vFAT Limits: Many external drives and cloud storage mounts use vFAT. These filesystems have a strict 255-byte limit for filenames and do not allow certain characters like colons (:), asterisks (*), or question marks (?). They are also case-insensitive, which can cause conflicts.
  • NTFS Quirks: While Linux can read NTFS, writing to it via smbclient or specific mount options may reject reserved Windows filenames like AUX, NUL, or CON.
  • Ext4/XFS Constraints: These modern Linux filesystems support very long names (up to 255 bytes), but they do not allow null bytes (\0) within filenames. If your file contains binary data in its name, it will fail.

Detecting the Filesystem Type

Before attempting fixes, verify the filesystem type of your destination directory. Run the following command on the remote server:
df -T /path/to/destination
Look at the second column. If it says vfat, msdos, or ntfs, you are dealing with a filesystem that has stricter naming conventions than standard Linux ext4. If it says ext4 or xfs, the issue might be related to specific shell escaping errors rather than filesystem limits.

The Robust Solution: Using Tar Archives

The most effective way to bypass filename restrictions is to avoid sending individual files altogether. Instead, bundle them into a single archive. An archive file typically has a simple, short name that complies with all filesystem standards. Perform these steps on your local machine:
  1. Create a tarball: Use tar to compress your problematic files. The -czf flags create a gzip-compressed archive. Replace output.tar.gz with your desired archive name and list the files or directories you want to transfer.
tar -czf output.tar.gz file1.txt "file with spaces.txt" weird_name*
  • Transfer the archive: Now, use scp to move this single, safe file to the remote server.
scp output.tar.gz user@remote:/path/to/destination/
  • Extract on the remote server: Log into the remote server and extract the contents. The extraction process reconstructs the original filenames, including any long or special characters, directly from the archive metadata.
ssh user@remote "tar -xzf /path/to/destination/output.tar.gz -C /path/to/destination/"
This method works regardless of whether the destination is vFAT, NTFS, or Ext4. It preserves permissions and timestamps if you add the -p flag to the tar commands. For more details on managing large transfers, see our guide on Accessing a Linux Server with Credentials Managed via PAM: Copying Files Remotely using SCP.

Alternative: Renaming Files Before Transfer

If you cannot use archives due to disk space constraints or workflow requirements, you must sanitize the filenames before transferring. This involves renaming files to remove invalid characters and truncate long names. You can automate this with a bash script. Here is a basic example that removes non-alphanumeric characters and truncates names to 100 characters:
for f in *; do
    newname=$(echo "$f" | tr -cd '[:alnum:]._-')
    if [ ${#newname} -gt 100 ]; then
        newname="${newname:0:100}"
    fi
    mv -- "$f" "$newname"
done
After running this script, your files will have clean, short names that scp can handle easily. Remember to rename them back after extraction if needed. This approach is useful when moving Windows files to Unix locations, as discussed in Moving Windows Drive Files to Unix Location: A Comprehensive Guide.

Why SSH Buffer Settings Do Not Help

Some users attempt to resolve this by increasing SSH buffer sizes or adjusting MaxPacketSize in sshd_config. This is incorrect. The "Invalid argument" error occurs during the file creation phase on the destination filesystem, not during data transmission. Network buffers have no influence on whether the kernel accepts a filename. Adjusting these settings wastes time and does not address the underlying filesystem incompatibility. Always prioritize the tar archive method for reliability.

Handling Special Characters in Filenames

Even on compatible filesystems, special characters can cause issues if not escaped properly in the shell. When typing filenames manually, always enclose them in quotes or escape spaces with backslashes.
scp "my file.txt" user@host:/dest/
scp my\ file.txt user@host:/dest/
If you are scripting, use find with -print0 and xargs -0 to handle filenames with newlines or spaces safely. This prevents the shell from misinterpreting parts of the filename as separate arguments.

Debugging Persistent Errors

If the tar method still fails, check the remote server's logs. Use tail -f /var/log/auth.log or /var/log/syslog while attempting the transfer. Look for messages indicating permission denied or disk full. Occasionally, "Invalid argument" can mask a lack of write permissions if the user does not own the target directory. Ensure you have write access to the destination folder using ls -ld /path/to/destination. For troubleshooting other common SCP failures, such as broken pipes, refer to our article on Broken Pipe Error During File Transfer via SCP on DigitalOcean Droplet.

Frequently Asked Questions

Can I increase the filename length limit on vFAT?

No, the 255-byte limit is hardcoded into the FAT32 specification and cannot be changed by mounting options. You must shorten the names or use an archive format to bypass this limitation entirely.

Does scp support unicode filenames natively?

Yes, modern versions of OpenSSH support UTF-8 filenames. However, the remote filesystem must also support UTF-8 encoding. If the destination is a legacy Windows share or old vFAT drive, unicode characters may be rejected or corrupted.

What if I only have one file with a bad name?

You can simply rename it locally before transferring. Use the mv command to change the filename to something simple, transfer it, and then rename it again on the remote server after copying.

Is rsync better than scp for this problem?

Rsync handles filenames similarly to scp; it will also fail with "Invalid argument" if the destination filesystem rejects the name. Switching tools does not solve the underlying filesystem constraint issue.

How do I check if a filename contains null bytes?

Use the find command with -name '*[^[:print:]]*' or inspect files with ls -b to show non-printable characters. Null bytes cannot exist in Linux filenames and will always cause transfer errors.

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