How to Compress Folders in FreeBSD Using Find and Tar
In this guide, I’ll walk you through a simple method to compress all directories in your current folder using FreeBSD. The challenge comes when you want to ensure the compression process works on FreeBSD, a system with some differences in its shell behavior compared to Linux.
Why This Approach?
In FreeBSD, the default shell (usually sh
or tcsh
) behaves a little differently from bash
, which is common in Linux. The typical approach of using for
loops with variable expansion might not work as expected. This guide provides a foolproof method using the find
command and a small shell script to handle directory compression.
The Command:
Here’s the one-liner command that will find all the directories in the current folder and compress each one into a .tar.bz2
file, named in the format <folder_name>_<YYYYMMDD>.tar.bz2
:
find . -type d -depth 1 -exec sh -c 'dir="{}"; name=$(basename "$dir"); tar -cjf "${name}_$(date +%Y%m%d).tar.bz2" "$dir"' \;
How It Works:
find . -type d -depth 1
: This part of the command finds all directories in the current directory (without recursion).-exec sh -c '...'
: This executes a shell command for each directory found byfind
.- Shell command breakdown:
dir="{}"
: Assigns the current directory path found byfind
to a variable.name=$(basename "$dir")
: Extracts just the directory name (without the full path).tar -cjf "${name}_$(date +%Y%m%d).tar.bz2" "$dir"
: Compresses the directory into a.tar.bz2
file using the current date as part of the filename.
Why Use This Method?
This approach avoids potential issues with loop syntax in FreeBSD and handles directory names with spaces or special characters. Additionally, it uses the reliable find
command to perform directory traversal in a system-independent way, making it more robust for FreeBSD environments.
If you still encounter issues, here are a few things to check:
- The exact error message you’re seeing.
- The output of
echo $SHELL
to verify which shell you are using. - The output of
sh --version
orecho $SHELL_VERSION
(if available) for additional version information.
This information will help further diagnose any specific issues on your FreeBSD system.