tar over ssh: Set destination file name and locati

2019-09-20 13:12发布

问题:

The easiest way to explain this question is show the following line of code which I have in a bash script.

tar -cJf - ./my_folder | ssh user@example 'tar -xJf - && rm -r ./path-to-my_folder/my_folder && mv ./my_folder ./path-to-my_folder'

I don't fully understand how it works. (What does '-' mean in this context?) But this is what it does:

  • Creates a compressed tar archive in memory and the pipe somehow pushes the tar data over ssh

  • The tar archive appears in users root folder, it is extracted

  • The ssh command continues executing the stuff in the between ' ... ', the old folder on the server side is removed using rm and replaced by moving the extracted folder from the user's root directory

It is obvious that this is a rather long way of doing things. It would be better if the tar archive was extracted to the correct location so that the rm and mv commands would not be necessary. Can this be done?

Note: I cannot use rsync.

回答1:

Try this:

tar -cJf - ./my_folder | ssh user@example 'tar -xJf - -C path-to-my_folder'

The - sign mean STDOUT. But in modern tar implementation, STDOUT is default output, so -f - could be omited:

tar -cJ my_folder | ssh user@example 'tar -xJC path-to-my_folder'

The -J switch mean xz compression, wich could be overkill on small configuration (like raspberry-pi, android and many embed systems), so you could obtain better performances by using -z switch for gzip compression:

tar -zc my_folder | ssh user@example 'tar -zxC path-to-my_folder'