tar - macOS
Overview
tar
is a powerful command-line utility on macOS used for creating, modifying, and extracting archive files. These archives can be compressed or uncompressed, providing a convenient way to store multiple files or directories as a single package.
Syntax
tar [options] [command] [archive-name] [files/directories]
Options/Flags
Creation Options:
- -c: Create a new archive
- -v: Verbose output during creation
- -z: Compress the archive using GZIP
- -j: Compress the archive using BZIP2
- -P: Preserve file permissions
Extraction Options:
- -x: Extract the archive
- -t: List the archive’s contents
- -r: Append files to an existing archive
- -f: Specify the archive file to work on
- -p: Preserve file permissions during extraction
- -C: Change to the specified directory before extracting
Common Options:
- -h: Display help information
- -V: Display version information
- –ignore-failed-read: Ignore read errors
- –exclude: Exclude files/directories from the archive
- –include: Only include files/directories matching the pattern
Examples
Create a compressed archive:
tar -czf my_archive.tar.gz /path/to/files
Extract the archive to the current directory:
tar -xf my_archive.tar.gz
List the archive’s contents:
tar -tf my_archive.tar.gz
Append files to an existing archive:
tar -rf my_archive.tar.gz /path/to/more_files
Extract the archive to a specific directory:
tar -C /destination/dir -xf my_archive.tar.gz
Common Issues
- Permission denied: Ensure you have the necessary permissions to access the archive or extract files.
- File not found: Check the path and spelling of the archive file.
- Invalid file format: The archive may be corrupted or created using an unsupported format.
Integration
tar
can be integrated with other commands for advanced tasks:
-
Find files within the archive:
tar tvf my_archive.tar.gz | grep filename
-
Extract specific files using a script:
for file in $(tar -tf my_archive.tar.gz); do tar -xf my_archive.tar.gz $file; done
Related Commands
- zip: A compression and archiving tool
- 7z: An open-source file archiver with high compression ratios
- pkzip: A popular commercial file archiving tool