Created
February 22, 2017 17:01
-
-
Save jasom/cf2abb8937a94f4aca5e584acc51c1de to your computer and use it in GitHub Desktop.
Network copy with tar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
usage() { | |
cat <<EOF >&1 | |
Usage: $1 [OPTION].. SRC DSTDIR | |
Recursively copy SRC to destination directory DSTDIR. | |
-f Create DSTDIR if it does not exist | |
-H FORMAT Use tar format FORMAT (default=pax) | |
Format for SRC and DSTDIR: | |
[[user@]hostname:]path | |
EOF | |
} | |
quote() { | |
togo="$1" | |
printf "'" | |
while test -n "$togo"; do | |
noq="${togo%%\'*}" | |
printf '%s' "$noq" | |
if test "$noq" '!=' "$togo"; then | |
printf "'%s'" "\\'" | |
togo="${togo#*\'}" | |
else | |
break | |
fi | |
done | |
printf "'" | |
} | |
format=pax | |
sremote="" | |
dremote="" | |
force="" | |
while getopts "hfH:" opt; do | |
case "$opt" in | |
h) | |
usage "$@" | |
exit 3 | |
;; | |
f) | |
force=yes | |
;; | |
H) | |
format="$OPTARG" | |
;; | |
\?) | |
printf '%s\n' "Invalid option: -$OPTARG" >&2 | |
usage "$@" | |
exit 1 | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
if test $# -lt 2; then | |
printf 'No destination specified\n' | |
usage "$@" | |
exit 2; | |
fi | |
src="$1" | |
dst="$2" | |
if printf '%s' "$src" |grep -q "[:]"; then | |
sremote="${src%:*}" | |
src="${src##*:}" | |
fi | |
if printf '%s' "$dst" |grep -q "[:]"; then | |
dremote="${dst%:*}" | |
dst="${dst##*:}" | |
fi | |
createCmd="$(printf 'tar -H %s -C %s -c %s' "$(quote "$format")" "$(quote "$(dirname "$src")")" "$(quote "$(basename "$src")")")" | |
extractCmd="$(printf 'tar -C %s -x' "$(quote "${dst}")")" | |
if test -n "$force"; then | |
extractCmd="$(printf 'mkdir -p %s; %s' "$(quote "$dst")" "$extractCmd")" | |
fi | |
{ | |
if test -z "$sremote"; then | |
eval "$createCmd" | |
else | |
#shellcheck disable=SC2029 | |
ssh "$sremote" "$createCmd" | |
fi | |
} | | |
{ | |
if test -z "$dremote"; then | |
eval "$extractCmd"; | |
else | |
# shellcheck disable=SC2029 | |
ssh "$dremote" "$extractCmd" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment