tar

tar #

Usage #

text
tar -c [-f ARCHIVE | -O] [OPTIONS] [FILE...]
    Create

tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...]
    Extract

tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...]
    Test

tar -d [-f ARCHIVE] [OPTIONS] [FILE...]
    Diff


tar -A [OPTIONS] ARCHIVE ARCHIVE
    Append archive to the end of another archive.

tar -r [-f ARCHIVE] [OPTIONS] [FILE...]
    Append files to the end of an archive.

tar -u [-f ARCHIVE] [OPTIONS] [FILE...]
    Append files which are newer than the corresponding copy in the archive.

tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...]
    Delete from archive.

Example: create/extract #

bash
# Create:
tar -cf dist.tar dist
tar -czf dist.tar.gz dist
tar -czO dist | command_to_handle_tar_gz...

# Extract:
tar -xf dist.tar
tar -xf dist.tar dist/README.md
tar -xf dist.tar.gz
tar -xzf dist.tar.gz

Example: change dir before create/extract #

bash
# Create from path/to/parent-dir/dist:
tar -cf dist.tar -C path/to/parent-dir dist -C another-dir index.html

# Test:
tar -tf dist.tar
# Output:
# dist/
# dist/README.md
# index.html

# Test (verbose):
tar -vtf dist.tar

# Extract to path/to/target-dir/dist:
tar -xf dist.tar -C path/to/target-dir

Example: exclude files #

bash
# Example 1: Create from dirA/distA and dirB/distB excluding README.md:
tar -cf dist.tar  -C dirA --exclude=distA/README.md distA  -C dirB --exclude=distB/README.md distB

# Test:
tar -tf dist.tar
# Output:
# distA/
# distA/index.html
# distB/
# distB/index.html

# Example 2:
tar -cf dist.tar  --exclude README.md dist

Example: copy/backup over ssh channel #

bash
# Copy files from hostA to hostB
ssh hostA 'tar -cz -C path/to/parent-dir dist' | ssh hostB 'tar -xzv -C path/to/target-dir'
# Equals to scp: (ssh+tar is faster for large number of small files)
scp -3 -r hostA:path/to/parent-dir/dist hostB:path/to/target-dir/

# Backup files from remotehost to localhost
ssh remotehost 'tar -cz -C path/to/parent-dir dist' > path/to/target-dir/dist.tar.gz

# Backup files from localhost to remotehost
tar -cz -C path/to/parent-dir dist | ssh remotehost 'cat > path/to/target-dir/dist.tar.gz'
2025年7月21日