Wednesday, March 30, 2011

How do I copy a directory structure from one machine to another?

 $ tar cf - some_directory | ssh kramer "( cd /path/to/destination; tar xf - )"

tar cf – some_directory creates a tar file of some_directory but the dash tells tar to write to STDOUT instead of writing to an actual file on disk. The STDOUT from the first tar command is piped to STDIN of the next command. The right hand side of the pipe says to log into the host kramer using ssh and run the commands cd and tar xf -. The trick is with the commands “( cd /path/to/destination; tar xf – )”. The parens create a subshell, in which the current directory is changed to /path/to/destination, and tar xf – reads from STDIN and extracts the tar file. This STDIN is the same STDIN that was sent to us over the pipe from STDOUT of the first tar command. Thus the directory structure on jerry gets tar’d up, transfered to kramer, then extracted all in one fell swoop.