Sync Filesystem: Wait Done - Export Logs to USB Drive

Abstract: Resolve data corruption risks when exporting logs to USB by using the sync command to flush filesystem buffers before copying files.

Created: 2026-08-24 by
To safely export system logs to a USB drive, you must first ensure all pending data is written from memory to the physical storage. Use the sync command to flush the filesystem buffers, then mount the USB device and copy the log files using standard tools like cp or rsync. This two-step process prevents data corruption and ensures that your archived logs are complete and accurate for future analysis or compliance auditing.

Why Syncing is Critical Before Copying

Modern Linux systems use a write-back caching mechanism to improve performance. When you modify files, the changes are often stored in RAM first rather than being immediately written to the disk. If you unplug a USB drive or remove it without syncing, any recent changes might remain only in the volatile memory. This can lead to partial files, corrupted archives, or missing critical error entries in your exported logs. The sync command forces the kernel to push all dirty pages (modified data) from the page cache to the underlying block devices. It does not take arguments; it simply executes against all mounted filesystems. While modern desktop environments often sync automatically when you eject media, server-grade systems or scripts require explicit synchronization to guarantee data integrity. Without this step, you risk exporting an inconsistent state of your system's history.

Distinguishing Sync from Unmount

It is important to understand that sync is different from umount. The umount command detaches the filesystem from the directory tree, which also triggers a sync operation internally. However, if you are copying files *to* the USB drive, you need to sync the destination before removing it. If you are reading logs *from* the local system to copy elsewhere, you should sync the local filesystem to ensure the source data is stable. In most export scenarios, syncing both the source and destination provides the highest level of safety.

Step-by-Step Guide to Exporting Logs

Follow these steps to securely transfer your logs. We assume you have root privileges or appropriate permissions to read the log directories.
  1. Identify Your Log Directory: Most system logs reside in /var/log. Verify the contents by running ls -l /var/log.
  2. Prepare the USB Drive: Insert the USB drive. Identify its mount point using df -h or lsblk. Common mount points include /media/username/USB_LABEL or /mnt/usb.
  3. Synchronize the Filesystem: Run the following command to flush all caches:
    sudo sync
    This command returns control to your shell only after all writes are physically completed.
  4. Copys the Files: Use rsync for a robust transfer that handles errors gracefully. Create a backup folder on the USB drive first:
    mkdir -p /path/to/usb/logs_backup
    rsync -av /var/log/ /path/to/usb/logs_backup/
    The -a flag preserves permissions and timestamps, while -v provides verbose output so you can monitor progress.
  5. Verify and Eject: Once rsync completes, run sync again to ensure the USB drive has finished writing the new files. Then, safely remove the hardware using your desktop environment's eject button or the eject command.

Handling Large Log Archives

System logs can grow significantly over time, especially on busy servers. Copying thousands of small files individually can be slow and inefficient. Instead, consider compressing the logs into a single archive before transferring them. This reduces I/O overhead and makes the resulting file easier to manage. You can create a compressed tarball directly on the USB drive or locally before copying. To create a gzip-compressed archive of your logs:
tar -czvf /path/to/usb/system_logs.tar.gz -C / var/log
This command changes directory to /, targets var/log, and creates a compressed archive at the specified path on the USB drive. Always remember to run sync after creating large archives to ensure the compression process finishes writing to the disk. For more information on managing external storage issues, such as fixing mounting problems or running filesystem checks, refer to our guide on Fixing External Storage Mounting Issues in Linux: A Guide to Using 'force' and 'fsck' Commands. This resource helps troubleshoot cases where the USB drive fails to mount correctly due to filesystem inconsistencies.

Automating Log Exports with Cron

If you need to regularly export logs, manual execution is prone to human error. You can automate the process using cron. Create a script that performs the sync, copy, and verification steps, then schedule it to run weekly or monthly. Ensure the script includes error handling so you are notified if the USB drive is not present or if the copy fails. When scripting, always use absolute paths for the USB mount point to avoid ambiguity. Additionally, consider rotating old logs on the USB drive to prevent it from filling up. Tools like logrotate can help manage the size of the exported data over time. For advanced monitoring of filesystem events during these operations, you might find Monitor Filesystem Events with inotify-tools and Daemonwatch useful. This article explains how to watch for changes in real-time, which can be helpful for debugging why certain logs might be delayed or locked during the export process.

Troubleshooting Common Issues

If the sync command appears to hang, check for processes that are actively writing to the disk. Use iostat -x 1 to monitor I/O activity. High await times indicate that the disk is struggling to keep up, which is normal for slow USB 2.0 drives but may indicate hardware failure on high-speed interfaces. If you encounter permission denied errors during the copy, ensure you are running the commands with sudo or that your user account has read access to /var/log. Some log files, such as those in /var/log/journal, may require specific group memberships or systemd-journal flags to access.

Frequently Asked Questions

Does the sync command wait for all disks?

Yes, the sync command waits until all modified blocks in the buffer cache are written out to the corresponding disk. It affects all currently mounted filesystems, ensuring that no data remains solely in RAM.

Can I skip sync if I use umount?

Technically, umount performs a sync operation before detaching the filesystem. However, relying on this behavior is risky if other processes are still writing to the disk or if the system crashes during the unmount. Explicitly calling sync is safer for critical data exports.

What happens if I pull the USB drive too early?

Pulling the drive prematurely can result in a "dirty" filesystem state. The next time you plug it in, the system may detect inconsistencies and refuse to mount it automatically, requiring a manual fsck to repair potential corruption.

Is rsync better than cp for this task?

rsync is generally preferred because it supports resuming interrupted transfers and provides detailed status updates. It also handles symbolic links and special files more predictably than basic cp commands, making it ideal for log archives.

How do I verify the logs were copied correctly?

After copying, compare the file count and total size of the source and destination directories. You can use diff -r /source /destination to check for discrepancies, although this may be slow for very large directories.

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