Commands.page Logo

How to Compress Directories with Spaces in Ubuntu

When working with Ubuntu, filenames containing spaces often cause errors during compression tasks if not handled correctly. This article explains the proper methods to compress directories and files with spaces in their names using common command-line tools like tar and zip. You will learn how to use quoting and escaping techniques to ensure your archives are created successfully without data loss or command failures.

Use Quotation Marks

The simplest way to handle spaces is to wrap the filename or directory path in quotation marks. This tells the shell to treat the entire string as a single argument. You can use either double or single quotes.

tar -czvf archive.tar.gz "my folder"
zip -r archive.zip "my folder"

Escape Spaces with Backslashes

Alternatively, you can escape each space with a backslash. This method is useful when you are typing commands manually and want to avoid switching quote types.

tar -czvf archive.tar.gz my\ folder

Handling Spaces in Scripts

When writing bash scripts to compress multiple directories, spaces can break loops if not managed properly. Always quote your variables to preserve whitespace.

for dir in "folder one" "folder two"; do
    tar -czvf "${dir}.tar.gz" "$dir"
done

Using find with print0 and xargs -0 is the most robust method for batch processing. This ensures null-terminated strings are used, preventing issues with spaces and special characters.

find . -maxdepth 1 -type d -print0 | xargs -0 -I {} tar -czvf {}.tar.gz {}

By following these practices, you ensure that Ubuntu compression commands interpret filenames accurately regardless of spaces.