Compress a directory using tar/gz over SSH to local computer?

17,614

You can do it with an ssh command, just tell tar to create the archive on its standard output:

ssh remote.example.com 'cd /path/to/directory && tar -cf - foo | gzip -9' >foo.tgz

Another approach, which is more convenient if you want to do a lot of file manipulations on the other machine but is overkill for a one-shot archive creation, is to mount the remote machine's filesystem with SSHFS (a FUSE filesystem). You should enable compression at the SSH level.

mkdir ~/net/remote.example.com
sshfs -C remote.example.com:/ ~/net/remote.example.com
tar -czf foo.tgz -C ~/net/remote.example.com/path/to/directory foo
Share:
17,614

Related videos on Youtube

Naftuli Kay
Author by

Naftuli Kay

Updated on September 18, 2022

Comments

  • Naftuli Kay
    Naftuli Kay over 1 year

    I'd like to essentially tar/gz a directory on a remote machine and save the file to my local computer without having to connect back into my local machine from the remote one. Is there a way to do this over SSH? The tar file doesn't need to be stored on the remote machine, only on the local machine. Is this possible?

  • phemmer
    phemmer almost 11 years
    I'm just curious, why'd you recommend tar -cf - foo | gzip -9 instead of tar -czf - foo or tar -cz foo?
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' almost 11 years
    @Patrick Slightly more portable, e.g. it'll work on Solaris.
  • Rootical V.
    Rootical V. almost 8 years
    Would you be so kind to describe all arguments?
  • arekolek
    arekolek over 7 years
    @RooticalV. tar -cf - foo creates (-c) archive on the standard output (-f -) from file foo. gzip -9 uses the best (slowest) compression method. If you don't care, you can just use ssh remote.example.com tar cz /path/to/directory/foo > foo.tar.gz.
  • Kusalananda
    Kusalananda over 6 years
    This does not store the tar archive on the local machine, which was what was intended.
  • Pierre de LESPINAY
    Pierre de LESPINAY over 6 years
    This is for people landing on this question (like me) when searching how to copy something through SSH with compression. There is just this additional tar xz out of the pipe with a simpler and more readable example.
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 3 years
    @mhellmeier The command you posted does exclude foo/bar and the files beneath it, at least with GNU tar.